- An overview
Objectives
Write code to define, instantiate, and start new threads using both java.lang.Thread and java.lang.Runnable. Recognize conditions that might prevent a thread from executing. Write code using synchronized wait, notify, and notifyAll to protect against concurrent access problems and to communicate between threads. Define the interaction among threads and object locks when executing synchronized wait, notify, and notifyAll.
Threads
An object of java.lang.Thread Thread of execution. Ways to define a thread
Using class java.lang.Thread Using Interface java.lang.Runnable
What is a thread?
Its a separate line of execution. It has its own call stack. Handling of threads by JVM is different in different platforms. Its always better not to write code that is dependent on the JVM implementation of threads.
Defining a thread
Using java.lang.Runnable class MyRunnable implements Runnable { public void run() { System.out.println("Important job running in MyRunnable"); } }
Complete example
class NameRunnable implements Runnable { public void run() { System.out.println("NameRunnable running"); System.out.println("Run by " + Thread.currentThread().getName()); } } public class NameThread { public static void main (String [] args) { NameRunnable nr = new NameRunnable(); Thread t = new Thread(nr); t.setName("Fred");
t.start();
} }
Something to remember
Each thread will start, and each thread will run to completion. Thread Scheduler
Thread States
New Runnable Running Blocked Waiting Sleeping
Thread priorities
Thread priority should be set before actually starting the thread. Thread.MIN_PRIORITY (1) Thread.NORM_PRIORITY (5) Thread.MAX_PRIORITY (10)
Synchronization
Why do we need synchronization? How do we achieve synchronization?
Refer 32 and 33 page of kathy sierra
Deadlock
Thread Interaction
wait() notify() notifyAll()
wait(), notify(), and notifyAll() must be called from within a synchronized context! A thread cant invoke a wait or notify method on an object unless it owns that objects lock.
IllegalMonitorStateExcepti on
If the thread calling wait() method doesnt own the lock, then the above exception is throwed. Its not a checked exception and hence need not be caught explicitly.
Thank You