Java中线程通信方式七种

https://blog.csdn.net/qq_42411214/article/details/107767326

一:volatile
二:synchronized 临界区方式
ReentrantLock/Condition 消息队列方式
三:使用JUC工具类 CountDownLatch
四:基本LockSupport实现线程间的阻塞和唤醒
五:通过Socket网络通信
六:信号量机制(Semaphore):包括无名线程信号量和命名线程信号量
七:管道通信就是使用java.io.PipedInputStream 和 java.io.PipedOutputStream进行通信

 

 

1、waite notify通信

public class Test1 {

    private static boolean flag = false;
    private static Object lock = new Object();

    public static void main(String[] args) {
        Wait wait = new Wait();
        wait.start();
        Notify notify = new Notify();
        notify.start();
    }

    static class Wait extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                while (!flag) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("hello");
            }
        }
    }

    static class Notify extends Thread {
        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("notify thread start");
                lock.notify();
                flag = true;
            }
        }
    }

}

。。。

posted @ 2023-12-30 21:39  guoyu1  阅读(207)  评论(0编辑  收藏  举报