剖析Java线程之间的通信

作者: Java酸不酸 | 来源:发表于2019-04-27 15:56 被阅读4次

    案例

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

    需求分析

    • 线程间通信(控制线程的切换,也叫等待唤醒机制(A - 锁 - B))
      • notify(),唤醒同一锁的某个线程
      • notifyAll(),唤醒同一锁的全部线程
      • wait(),停止当前线程,释放锁
      • wait(long timeout),等到特定的时间,自动停止当前线程,释放锁

    代码

    • 定义一把公共锁
    public class MyLock {
        public static final Object LOCK = new Object();
    }
    
    • 定义两个线程,分别为:ThreadOne、ThreadTwo
    // 线程一
    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
    
    

    相关文章

      网友评论

        本文标题:剖析Java线程之间的通信

        本文链接:https://www.haomeiwen.com/subject/knzjgqtx.html