Java兩線程交替執行

/**
 * Created by Administrator on 2020/6/29.
 */
public class day02 {
    public static void main(String[] args){
        Printer p = new Printer();
        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print1();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        new Thread(){
            public void run(){
                while (true){
                    try {
                        p.print2();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }
}

class Printer{
    private int flag=1;
    public void print1() throws InterruptedException {
        synchronized (this){
            if(flag!=1){
                this.wait();
            }
            System.out.print("黑");
            System.out.print("馬");
            System.out.print("程");
            System.out.print("序");
            System.out.print("員");
            System.out.print("\n\r");
            flag=2;
            this.notify();
        }

    }

    public void print2() throws InterruptedException {
        synchronized (this){
            if(flag!=2){
                this.wait();
            }
            System.out.print("傳");
            System.out.print("智");
            System.out.print("博");
            System.out.print("客");
            System.out.print("\n\r");
            flag=1;
            this.notify();
        }

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章