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

    }
}

 

你可能感兴趣的:(Java学习)