wait/notify的应用--交替打印

在之前的文章,我们已经讲过了wait和notify的知识点,今天就通过线程之前协同工作,实现线程之间交替打印。

package com.example.test;

public class Test235 {
     private boolean flag =false;
    private Object lock = new Object();
    static Test235 ttt = new Test235();
        public static void main(String[] args) {
            MyThread235t1 t1 = new MyThread235t1(ttt);
            MyThread235t t2 = new MyThread235t(ttt);
            for(int i = 0;i<20;i++) {
                Thread tt1 = new Thread(t1);
                Thread tt2= new Thread(t2);
                tt1.start();
                tt2.start();
            }
        }
        public void printA() {
            synchronized (lock) {
                while(flag==false){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                flag=false;
                for(int i = 0;i<5;i++) {
                    System.out.println("AAAAA");
                }
                lock.notifyAll();
            }
        }
        public void printB() {
            synchronized (lock) {
                while(flag==true){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                flag=true;
                for(int i = 0;i<5;i++) {
                    System.out.println("BBBBB");
                }
                lock.notifyAll();
            }
        }
}

class MyThread235t implements Runnable{
    private Test235 tt;

    public MyThread235t(Test235 tt) {
        super();
        this.tt = tt;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        tt.printA();

    }

}

class MyThread235t1 implements Runnable{
     private Test235 tt;

        public MyThread235t1(Test235 tt) {
            super();
            this.tt = tt;
        }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        tt.printB();
    }

}

对于两个线程都需要操作的数据,因为每个线程执行的时候,会从内存中,拷贝该变量的值到自己线程的工作空间中,我们通过volatile这个关键字,来保证在一个线程中修改,会立即刷新主内存的值,这样就保证另外线程在读取的时候,出现问题。

猜你喜欢

转载自blog.csdn.net/venus321/article/details/79801967