2014년 2월 1일 토요일

자바쓰레드 wait, notify, synchronized예제, JAVA THREAD Wait, Notyfy, 쓰레드대기, 깨우기 , Thread Sleep, 자바쓰레드교육학원, JAVA THREAD교육강의강좌, 자바/JSP/스프링/마이바티스교육학원

자바쓰레드 wait, notify, synchronized예제, JAVA THREAD Wait, Notyfy, 쓰레드대기, 깨우기 , Thread Sleep, 자바쓰레드교육학원, JAVA THREAD교육강의강좌, 자바/JSP/스프링/마이바티스교육학원



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

댓글 없음:

댓글 쓰기