2个线程顺序工作

2个线程,一个线程先写,然后另外一个线程读,以此循环。

static int i = 8;
static Object obj = new Object();
public static void main(String[] args) throws InterruptedException {
    Thread read = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
                synchronized (obj) {
                    System.out.println("read:" + i);
                    
                    obj.notify();
                    
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    
                }
            }
        }
    });
    Thread write = new Thread(new Runnable() {
        @Override
        public void run() {
            for (int j = 0; j < 100; j++) {
                synchronized (obj) {
                    i = j;
                    System.out.println("write:" + i);
                    
                    obj.notify();
                    
                    try {
                        obj.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });
    write.setName("write");
    read.setName("read");
    
    write.start();
    Thread.sleep(10);
    read.start();
}
原文地址:https://www.cnblogs.com/allenwas3/p/8644690.html