1.1.5 线程通信

通信的方式

要想实现多个线程之间的协同,如:线程执行先后顺序、获取某个线程执行的结果等等。涉及到线程之间相互通信,分为下面四类:

  1. 文件共享

  2. 网络共享

  3. 共享变量

  4. jdk提供的线程协调API

    细分为: suspend/resume、wait/notify、park/unpark

文件共享

流程: 线程-1 写入数据到文件系统 线程-2从其中读取数据。

public class Demo5 {
    public static void main(String[] args) {
        //线程1 写入数据
        new Thread(() -> {
            try {
                while (true) {
                    Files.write(Paths.get("Demo6.log"),("当前时间为" + String.valueOf(System.currentTimeMillis())).getBytes());
                    Thread.sleep(1000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
        //线程2 读取数据
        new Thread(()->{
            try {
                while (true){
                    Thread.sleep(1000L);
                    byte[] allBytes = Files.readAllBytes(Paths.get("Demo6.log"));
                    System.out.println(new String(allBytes));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

共享变量

流程: 线程-1 写入数据 到内存中的变量content 再线程-2读取数据。

public class Demo5 {
    public static String context = "";
    public volatile static Boolean flag = true;
    public static void main(String[] args) throws InterruptedException {
        //线程1 写入数据
        Thread thread1 = new Thread(() -> {
            try {
                while (flag) {
                    context = "当前时间为:" + System.currentTimeMillis();
                    Thread.sleep(1000L);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        Thread.sleep(5000L);
        flag = false;
        //线程2 读取数据
        new Thread(()->{
            try {
                while (true){
                    Thread.sleep(1000L);
                    System.out.println(context);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

线程协作 - JDK API

JDK中对于需要多线程协作完成某一任务的场景,提供了对于API支持。

多线程协作的典型场景是: 生产者 - 消费者模型。(线程阻塞、线程唤醒)

API - 被弃用的suspend 和 resume

作用: 调用suspend挂起目标线程,通过resume可以恢复线程执行。

public class Demo6 {
    static Object baozhi = null;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(()->{
            while (baozhi == null){
                System.out.println("没有包子,进入等待");
                Thread.currentThread().suspend();
                System.out.println("买到包子,回家");
            }
        });
        Thread thread2 = new Thread(()->{
            while (baozhi == null){
                System.out.println("生产包子");
                baozhi = new Object();
                System.out.println("通知顾客来买包子");
                thread1.resume();
            }
        });
        thread1.start();
        Thread.sleep(1000L);
        thread2.start();
    }
}

运行结果:

没有包子,进入等待
生产包子
通知顾客来买包子
买到包子,回家

**被弃用的主要原因,容易写出死锁的代码。**需要注意调用顺序,而且suspend不会释放锁。

wait/notify机制

这些方法只能由同一对象锁的持有者线程调用,也就是写在同步块里面,否则会抛出IllegalMonitorStateException异常。

wait方法导致当前线程等待,加入该线程的等待集合中,并且放弃当前持有的对象锁。

notify/notifyAll方法唤醒一个或所有正在等待这个对象锁的线程。

注意: 虽然会wait自动解锁,但是对顺序由要求,如果在notify被调用之后,才开始wait方法的调用,线程会永远处于WAITING状态。

public class Demo6 {
    static Object baozhi = null;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(()->{
            while (baozhi == null){
                synchronized (lock){
                    System.out.println("没有包子,进入等待");
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("买到包子,回家");
                }
            }
        });
        Thread thread2 = new Thread(()->{
            while (baozhi == null){
                synchronized (lock){
                    System.out.println("生产包子");
                    baozhi = new Object();
                    System.out.println("通知顾客来买包子");
                    lock.notify();
                }
            }
        });
        thread1.start();
        Thread.sleep(1000L);
        thread2.start();
    }
}

park/unpark机制

线程调用park则等待“许可”,unpark方法为指定线程提供“许可”。

不要求park和unpack方法的调用顺序。

多次调用unpark之后,再调用park,线程会直接运行。

不会叠加,也就是说,连续多次调用park方法,第一次会拿到“许可”直接运行,后续调用会进入等待。

public class Demo6 {
    static Object baozhi = null;

    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            while (baozhi == null) {
                System.out.println("没有包子,进入等待");
                LockSupport.park();
                System.out.println("买到包子,回家");

            }
        });
        Thread thread2 = new Thread(() -> {
            while (baozhi == null) {
                System.out.println("生产包子");
                baozhi = new Object();
                System.out.println("通知顾客来买包子");
                LockSupport.unpark(thread1);
            }
        });
        thread1.start();
        Thread.sleep(1000L);
        thread2.start();
    }

注意: 虽然park/unpark不需要注意调用顺序,但park的时候是不会释放锁。

伪唤醒

在代码中用if语句来判断,是否进入等待状态,是错误的!!

官方建议应该在循环中检查等待条件,原因是处于等待状态的线程可能会收到错误警报和伪唤醒,如果不在循环中检查等待条件,程序就会在没有满足结束条件的情况下退出。

伪唤醒是指线程并非因为notify、notifyall、unpark等api调用而唤醒,是更底层原因导致的。

park 、 suspend 、 wait 方法都是native方法。

发布了17 篇原创文章 · 获赞 13 · 访问量 909

猜你喜欢

转载自blog.csdn.net/weixin_43871142/article/details/104323270