img
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);
t.start();
}
// synchronize calls to call()
public void run() {
synchronized(target) { // synchronized block
target.call(msg);
}
}
}
class Synch1 {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
} catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
Here, the call( ) method is not modified by synchronized. Instead, the synchronized
statement is used inside Caller's run( ) method. This causes the same correct output as the
preceding example, because each thread waits for the prior one to finish before proceeding.
Interthread Communication
The preceding examples unconditionally blocked other threads from asynchronous access
to certain methods. This use of the implicit monitors in Java objects is powerful, but you can
achieve a more subtle level of control through interprocess communication. As you will see,
this is especially easy in Java.
As discussed earlier, multithreading replaces event loop programming by dividing your
tasks into discrete, logical units. Threads also provide a secondary benefit: they do away
with polling. Polling is usually implemented by a loop that is used to check some condition
repeatedly. Once the condition is true, appropriate action is taken. This wastes CPU time.
For example, consider the classic queuing problem, where one thread is producing some
data and another is consuming it. To make the problem more interesting, suppose that the
producer has to wait until the consumer is finished before it generates more data. In a polling
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home