2014년 1월 15일 수요일

자바쓰레드 wait, notify, synchronized예제(자바책열심히보고공부하세요~ 자바화이팅) ,오라클자바커뮤니티강좌자바

자바쓰레드 wait, notify, synchronized예제(자바책열심히보고공부하세요~ 자바화이팅)



class SharedData
{
    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();
    }
    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
    }
}

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);
    }
}
class Reader extends Thread
{
    SharedData shared;
    public Reader(SharedData shared) {
        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();
    }
}

댓글 없음:

댓글 쓰기