Chapter 9: Threads Flashcards
What are the important thread methods?
- start (start a new thread)
- run (descirbes the thread job)
- sleep (pauses the thread)
- yield (return to the runnable pool, so other threads can run)
What are the two ways to define a threads behaviour?
Extend the Thread class Implement the Runnable interface
Considering MyThread contains the Threads behaviour (and extends Thread), what is the result of the following?
Thread t = new Thread(new MyThread()); t.start();
Compiles and runs fine.
Thread implements the Runnable interface by default, so a sub-class of Thread can be passed as the runnable to the new Thread object.
What are the four constructors for the Thread class?
new Thread(); new Thread(String name); new Thread(Runnable runnable); new Thread(Runnable runnable, String name);
How to get the currents Thread name?
Thread t = Thread.currentThread();
t.getName();
What is the result of the following:
Thread t1 = new Thread(); Thread t2 = new Thread(); t1.start(); t2.start(); t1.start();
Throws an IllegalThreadStateException
A Thread object can only be started once.
Describe the Thread lifecycle
Waiting/Blocked
New -> Runnable Running -> Dead
When can a thread go into the runnable state?
- When the start method has been called on the Thread object.
- When returing from a blocked, waiting, sleeping state.
When can a thread go into the running state?
When the thread scheduler choses the thread from the runnable thread as the currently executing proces.
What is the result?
public static void main(String... args) { System.out.println("start"); Thread.sleep(5*60*1000); System.out.println("end"); }
Compile error.
Missing try-catch or throws clause.
What is the result?
public static void main(String... args) { Thread t1 = new Thread(); Thread t2 = new Thread(); t1.sleep(1000); t1.start(); t2.start(); t2.sleep(1000); }
The current thread (not t1 or t2) will sleep for 1000 ms starts both the threads and then will sleep again for 1000 ms.
sleep() is a static method on the Thread class. So it will let the currently executing thread sleep.
How to set a Threads priority?
thread.setPriority(5);
For min, max and norm values use:
Thread.MIN_PRIORITY;
Thread.MAX_PRIORITY;
Thread.NORM_PRIORITY;
What does Thread.yield(); do?
Returnt he current thread to the runnable pool to give other threads with equal priorities a chance to run. No guarantees, the Thread scheduler may choose the same thread as the new running thread.
What does thread.join(); do?
The current thread stops executing and waits till the “joining” thread is finished.
What does the synchronized keyword do?
- Can be used on methods and code-blocks
- Only one thread can run a synchronized method from a particular instance at the same time.
- When a thread has a lock (meaning it is inside a synchronized method or block) No other thread can lock the object (enter a synchronized method or block).
- When a thread goes to sleep, it keeps the lock on a object.