Professional Documents
Culture Documents
Threads Sync7 PDF
Threads Sync7 PDF
Threads Sync7 PDF
Synchronization example
Wait and Notify
class SyncTest extends Thread {
String msg;
public SyncTest(String s) {
msg = s;
• Must be called inside synchonized method
start(); } or block of statements (on the synchronized
public void run() {
synchronized (SyncTest.class) {
object)
System.out.print(“[“ + msg); • a.wait()
try { Thread.sleep(1000); }
catch (InterruptedException e) {}; – gives up lock(s) on a
System.out.println(“]”); } – adds thread to wait set for a
}
public static void main(String [] args) { – suspends thread
new SyncTest(“Hello”); new SyncTest(“Synchronized”);
new SyncTest(“World”); } • a.wait(int m)
} – limits suspension to m milliseconds
CMCS 433, Spring 2002 - Adam Porter 5 CMCS 433, Spring 2002 - Adam Porter 6
A Better Solution
Changed example
void produce(Object o) {
while (bufFull) { synchronized (empty) {
synchronized void produce(Object o) {
try {empty.wait(); }
while (full) {
catch (InterruptedException e) { }
wait();
synchronized Object consume() { }}
if (full) notify(); } Object consume() {
while (!full) { obj = o; bufFull = true;
obj = o; full = true; while (!bufFull) { synchronized (full)
wait(); synchronized (full) {
notify(); {
if (!full) notify(); } full.notify(); }
} try { full.wait(); }
full = false; }
notify(); catch (InterruptedException e) {}
Use two objects, }}
Bad design – no return obj;
empty and full, to Object o = obj; bufFull = false;
guarantee about who }
allow two different synchronized (empty) {
will get woken up wait sets empty.notify(); }
CMCS 433, Spring 2002 - Adam Porter 9 CMCS 433, Spring 2002 - Adam Porter 10
}
CMCS 433, Spring 2002 - Adam Porter 11 CMCS 433, Spring 2002 - Adam Porter 12
Guidelines (cont.)