Java 杂谈Java程序员技术栈

剖析Java线程之间的通信

2019-04-27  本文已影响4人  Java酸不酸

案例

两个线程规律交替输出1,2,3,4,5,6....10

需求分析

代码

public class MyLock {
    public static final Object LOCK = new Object();
}
// 线程一
public class ThreadOne extends Thread {
    @Override
    public void run() {
        for (int i = 1; i <= 10; i += 2) {
            synchronized (MyLock.LOCK) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
                MyLock.LOCK.notify();
                try {
                    MyLock.LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

// 线程二
public class ThreadTwo extends Thread {
    @Override
    public void run() {
        for (int i = 2; i <= 10; i += 2) {
            synchronized (MyLock.LOCK) {
                System.out.println(Thread.currentThread().getName() + ": " + i);
                MyLock.LOCK.notify();
                try {
                    MyLock.LOCK.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        new ThreadOne().start();
        new ThreadTwo().start();
    }
}
Thread-0: 1
Thread-1: 2
Thread-0: 3
Thread-1: 4
Thread-0: 5
Thread-1: 6
Thread-0: 7
Thread-1: 8
Thread-0: 9
Thread-1: 10

上一篇下一篇

猜你喜欢

热点阅读