class SharedData
{
private boolean isNew = false;
private int data;
{
private boolean isNew = false;
private int data;
public synchronized void put(int data)
{
try {
while( isNew ) // new data?
wait(); // unlocked
} catch(InterruptedException e ) {}
this.data = data;
isNew = true;
notifyAll();
}
{
try {
while( isNew ) // new data?
wait(); // unlocked
} catch(InterruptedException e ) {}
this.data = data;
isNew = true;
notifyAll();
}
public synchronized int get()
{
try {
while( !isNew ) // already got?
wait(); // unlocked
} catch(InterruptedException e ) {}
isNew = false;
notifyAll(); // waiting threads cannot wake up
return data; // until this method exits
}
}
{
try {
while( !isNew ) // already got?
wait(); // unlocked
} catch(InterruptedException e ) {}
isNew = false;
notifyAll(); // waiting threads cannot wake up
return data; // until this method exits
}
}
class Writer extends Thread
{
private SharedData shared;
private int data;
public Writer(SharedData shared, int data) {
this.shared = shared;
this.data = data;
}
public void run() {
shared.put(data);
shared.put(data+1);
}
}
this.shared = shared;
this.data = data;
}
public void run() {
shared.put(data);
shared.put(data+1);
}
}
class Reader extends Thread
{
SharedData shared;
{
SharedData shared;
public Reader(SharedData shared) {
this.shared = shared;
}
public void run() {
while(true)
System.out.println( getName() + " got " + shared.get() );
}
}
this.shared = shared;
}
public void run() {
while(true)
System.out.println( getName() + " got " + shared.get() );
}
}
class Wait
{
public static void main(String[] args)
{
SharedData shared = new SharedData();
Reader r1 = new Reader(shared);
Reader r2 = new Reader(shared);
Writer w1 = new Writer(shared, 10);
Writer w2 = new Writer(shared, 20);
r1.start();
r2.start();
w1.start();
w2.start();
}
}
r2.start();
w1.start();
w2.start();
}
}
댓글 없음:
댓글 쓰기