Concurrency Lecture 4 Flashcards
What does the start() method do?
It initialises and allocates memory for a new thread. It also calls the run() method tied to that thread, making the thread eligible to be run by the JVM.
What are the two types of threads?
Daemon and non-daemon.
What is the difference between daemon and non-daemon threads?
The JVM shuts down when all non-daemon threads have executed and have exited.
How do you create a daemon thread?
By calling the setDaemon() method on the created thread, but before it has started.
thread. setDaemon();
thread. start();
Name the 6 thread states.
In no particular order:
- New
- Terminated
- Blocked
- Waiting
- Timed Waiting
- Runnable
How do you determine the start of a thread?
The isAlive() method returns true if the thread it is called on has not reached its terminated state, otherwise it returns true.
The getState() method returns the state of the method it is called on as an enumerated data type as one of the states.
What methods can make a thread go into a waiting state?
- wait() without a timeout
- join() without a timeout
- Lock Support.park
What methods can make a thread go into the timed Waiting state?
- sleep()
- wait() with a timeout
- join() with a timeout
- LockSupport.parkNanos
- LockSupport.parkUntil
What do the threads that are automatically created in the system group do?
Mostly managing object references.
What is a lock condition?
A condition created by the lock at the start of the object, which can be used to make a thread wait for something to happen, allowing another thread to run and possible notify the awaiting thread that the condition has been met.
E.g. Insufficient funds in a bank, so await for a thread that runs the top up method to signal it.
What code do we write to use a condition for a lock?
Instance:
private Condition cond;
Constructor creation (Creates new condition for the fundsLock lock, assume we have created) : cond = fundsLock.newCondition();
In 'withdraw' method: Boolean stillWaiting = true; // lock ... while (funds < amount) { If (!stillWaiting) { Thread.currentThread().interrupt(); } stillWaiting = cond.await(10, TimeUnit.SECONDS); // Condition waits 10 or until signalled by other thread. } ... // unlock
In 'deposit' method: // lock ... // Critical code cond.signalAll(); // unlock
Explain the new state for a thread.
A thread in this state is a thread which has been created (instantiated) but not yet started.
Explain the terminated state.
A thread is in this state when it’s run() method has ended.
Explain the blocked state.
A thread is in this state when it waits to aquire a lock
Explain the waiting state.
When a thread is waiting for an action by another thread. For example, it has invoked a wait method without a timeout.and is now waiting.