1. 程式人生 > >實現執行緒間的通訊(一)

實現執行緒間的通訊(一)

notify()和wait()實現:

this.notify():隨機喚醒單個等待執行緒。

this.wait():當前執行緒等待,wait()若無人喚醒,則一直等待;而Thread.sleep是睡眠一定時間後再次啟動。

 


public class DemoNotify {

    public static void main(String[] args) {
        final Print p=new Print();
        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print1();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print2();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}
class Print{
    private int flag=1;
    public void print1() throws Exception{
        synchronized(this){
            if (flag!=1){
                this.wait();            //當前執行緒等待,wait()若無人喚醒,則一直等待;而Thread.sleep是睡眠一定時間後再次啟動
                System.out.println("等待一");
            }
            System.out.print("1");
            System.out.print("2");
            System.out.print("3");
            System.out.print("4");
            System.out.println("5");
            flag=2;
            this.notify();          //隨機喚醒單個等待執行緒
        }
    }
    public void print2() throws Exception{
        synchronized(this){
            if (flag!=2){
                this.wait();
                System.out.println("等待二");
            }
            System.out.print("上");
            System.out.print("山");
            System.out.print("打");
            System.out.print("老");
            System.out.println("虎");
            flag=1;
            this.notify();
        }
    }
}

執行結果:

12345
上山打老虎
等待一
12345
等待二
上山打老虎
等待一
12345
等待二
上山打老虎
等待一