

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Project; Professor: Sussman; Class: PROG LANG TECH & PDGMS; Subject: Computer Science; University: University of Maryland; Term: Spring 2002;
Typology: Study Guides, Projects, Research
1 / 3
This page cannot be seen from the preview
Don't miss anything!


CMCS 433, Spring 2002 - Alan Sussman 2
CMCS 433, Spring 2002 - Alan Sussman 3
CMCS 433, Spring 2002 - Alan Sussman 4
class SyncTest extends Thread { String msg; public SyncTest(String s) { msg = s; start(); } public void run() { synchronized (SyncTest.class) { System.out.print(“[“ + msg); try { Thread.sleep(1000); } catch (InterruptedException e) {}; System.out.println(“]”); } } public static void main(String [] args) { new SyncTest(“Hello”); new SyncTest(“Synchronized”); new SyncTest(“World”); } }
CMCS 433, Spring 2002 - Alan Sussman 5
CMCS 433, Spring 2002 - Alan Sussman 7
public class ProducerConsumer { private boolean ready = false; private Object obj; public ProducerConsumer() { } public ProducerConsumer(Object o) { obj = o; ready = true; } synchronized void produce(Object o) { while (ready) wait(); obj = o; ready = true; notifyAll(); }
synchronized Object consume() { while (!ready) wait(); ready = false; notifyAll(); return obj; } } CMCS 433, Spring 2002 - Alan Sussman 8
synchronized void produce(Object o) { while (ready) { wait(); if (ready) notify(); } obj = o; ready = true; notify(); }
synchronized Object consume() { while (!ready) { wait(); if (!ready) notify(); } ready = false; notify(); return obj; }
Doesn’t work well – no guarantee about who will get woken up
CMCS 433, Spring 2002 - Alan Sussman 9
synchronized void produce(Object o) { while (ready) { synchronized (empty) { try {empty.wait(); } catch (InterruptedException e) { } }} obj = o; ready = true; synchronized (full) { full.notify(); } }
synchronized Object consume() { while (!ready) { synchronized (full) { try { full.wait(); } catch (InterruptedException e) { }} Object o = obj; ready = false; synchronized(empty){ empty.notify(); } return obj; }
Use two objects, empty and full , to allow two different wait sets CMCS 433, Spring 2002 - Alan Sussman 10
CMCS 433, Spring 2002 - Alan Sussman 11