Java Threads
Java Threads
Resources
Java Threads by Scott Oaks & Henry Wong (OReilly) API docs
http://download.oracle.com/javase/6/docs/api/ java.lang.Thread, java.lang.Runnable java.lang.Object, java.util.concurrent
Tutorials
http://download.oracle.com/javase/tutorial/essential/concurrency/index.html http://download.oracle.com/javase/tutorial/essential/concurrency/procthread.html
Thread safety
http://en.wikipedia.org/wiki/Thread-safety
http://www.javaworld.com/jw-08-1998/jw-08-techniques.html
1
Coverage
Thread class
run, start methods yield, join sleep
Synchronization
synchronized methods & objects wait/notify/notifyAll conditions
2
java.lang.Thread
Two techniques to create threads in java 1) implementing the Runnable interface
The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method, called run, with no arguments. invoke Thread constructor with an instance of this Runnable class See pages 162 and 164 in text for an example
2) extending Thread
Define a subclass of java.lang.Thread
Define a run method
In another thread (e.g., the main), create an instance of the Thread subclass
Then, call start method of that instance
3
Example 1
Create 2 threads from the Main, then start them Threads will be instances of different thread sub-classes
class MyThreadA extends Thread { public void run() { // entry point for thread for (;;) { System.out.println("hello world1"); } } }
class MyThreadB extends Thread { public void run() { // entry point for thread for (;;) { System.out.println("hello world2"); } } }
public class Main1 { public static void main(String [] args) { MyThreadA t1 = new MyThreadA(); MyThreadB t2 = new MyThreadB(); t1.start(); t2.start();
// main terminates, but in Java the other threads keep running // and hence Java program continues running
} }
5
hello world2 hello world2 hello world1 hello world2 hello world1 hello world2 hello world2 hello world1 hello world1 hello world1 hello world1 hello world2 hello world1 hello world1 hello world2 hello world2 hello world1 hello world1 hello world2 hello world2 hello world1 hello world1 hello world2
Example 2
Create 2 threads from the Main, then start them Threads will be instances of the same thread sub-class Use argument of constructor of new thread class to pass text name of thread, e.g., thread1 and thread2
Data member provides different data per thread (i.e., then name) A data member can also be used to share data
7
class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }
thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread2: hello world thread1: hello world thread2: hello world thread2: hello world
See the variation in output: This variation in output is called a race condition (often race conditions are bugs in programs)
java.lang.Thread
public static void yield();
Method of java.lang.Thread Thread gives up CPU for other threads ready to run
10
class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; }
public void run() { for (;;) { System.out.println(name + ": hello world"); yield(); } }
} public class Main3 { public static void main(String [] args) { MyThread t1 = new MyThread("thread1"); MyThread t2 = new MyThread("thread2"); t1.start(); t2.start(); } }
11
thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world thread2: hello world thread1: hello world
Some Output
Join Example
14
hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 hello world1 Thread is done!
Some output
15
Thread State
public Thread.State getState()
Returns the state of this thread. This method is designed for use in monitoring of the system state, not for synchronization control
http://java.sun.com/javase/6/docs/api/java/lang/Thread.State.html
Scheduling
Priority inherited from parent, but can be changed Higher priority threads generally run before lower priority threads For equal priority threads, best to call yield() intermittently to handle JVMs with user-level threading (i.e., no time-slicing)
17
18
Used on a per method basis; not all methods in a class have to have this
But, youll need to design it right!!
19
20
Typically used within a loop to re-check a condition wait(long millis); // bounded wait
21
For notify, if more than one thread available to be woken, then one is picked
22
InterruptedException
Wait can be woken by the exception, I.e., for reasons other than notify Sometimes this can be handled as part of the process of re-checking conditions There is another way to handle it too
23
Synchronized Blocks
Synchronized methods
Implicitly lock is on this object
Synchronized blocks
lock on an arbitrary, specified object similar to condition variables in monitors but need to have a synchronized block around an object before wait/notify used use wait/notify on the object itself
24
Syntax
synchronized (object) { // object.wait() // object.notify() // object.notifyAll() } For example, this allows you to synchronize just a few lines of code, or to synchronize on the basis of an arbitrary object
25
public class Deadlock { public static void main(String[] args) { // These are the two resource objects we'll try to get locks for final Object resource1 = "resource1"; final Object resource2 = "resource2"; // Here's the first thread. It tries to lock resource1 then resource2 Thread t1 = new Thread() { public void run() { // Lock resource 1 synchronized(resource1) { System.out.println("Thread 1: locked resource 1"); try { Thread.sleep(50); } catch (InterruptedException e) {} // Now wait 'till we can get a lock on resource 2 synchronized(resource2) { System.out.println("Thread 1: locked resource 2"); } } } };
// Here's the second thread. It tries to lock resource2 then resource1 Thread t2 = new Thread() { public void run() { // This thread locks resource 2 right away synchronized(resource2) { System.out.println("Thread 2: locked resource 2"); // Then it pauses, for the same reason as the first thread does try { Thread.sleep(50); } catch (InterruptedException e) {} synchronized(resource1) { System.out.println("Thread 2: locked resource 1"); } } } }; t1.start(); t2.start(); } }