并发编程系列教程(06) - 多线程之间通讯(wait、notify、sleep、Lock锁、Condition)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_20042935/article/details/102703363

代码已上传到Github,有兴趣的同学可以下载来看(https://github.com/ylw-github/Java-ThreadDemo

1. 什么是多线程之间通讯?

多线程之间通讯,其实就是多个线程在操作同一个资源,但是操作的动作不同。

2. 多线程之间的通讯需求

需求:第一个线程写入(input)用户,另一个线程取读取(out)用户,实现读一个,写一个操作。
在这里插入图片描述

3. 代码实现

package com.ylw.thread;

public class ThreadMsgDemo {

    //1.共享资源实体类
    public static class Res {
        private String userName;
        private String sex;
    }

    //2.读取线程
    public static class InThread extends Thread {

        private Res res;
        int count = 0;

        public InThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                if (count == 0) {
                    res.userName = "小明";
                    res.sex = "男";
                } else {
                    res.userName = "小红";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
            }
        }
    }

    //3.写入线程
    public static class OutThread extends Thread {
        private Res res;

        public OutThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                System.out.println(res.userName + "----" + res.sex);
            }
        }
    }

    public static void main(String[] args) {
        Res res = new Res();
        InThread inThread = new InThread(res);
        OutThread outThread = new OutThread(res);
        inThread.start();
        outThread.start();
    }
}

运行结果,会发现数据发生错乱,造成线程安全的问题:
在这里插入图片描述

3.1 解决线程安全问题

输入和输出线程加上同步synchronized,如下代码:

//2.读取线程
public static class InThread extends Thread {

    private Res res;
    int count = 0;

    public InThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        super.run();
        while (true) {
            synchronized (res){//同步加锁,解决多线程安全问题
                if (count == 0) {
                    res.userName = "小明";
                    res.sex = "男";
                } else {
                    res.userName = "小红";
                    res.sex = "女";
                }
                count = (count + 1) % 2;
            }
        }
    }
}

//3.写入线程
public static class OutThread extends Thread {
    private Res res;

    public OutThread(Res res) {
        this.res = res;
    }

    @Override
    public void run() {
        super.run();
        while (true) {
            synchronized (res){//同步加锁,解决多线程安全问题
                System.out.println(res.userName + "----" + res.sex);
            }
        }
    }
}

运行结果,正常:
在这里插入图片描述

4. wait、notify方法

1.因为涉及到对象锁,他们必须都放在synchronized中来使用。 wait、notify一定要在synchronized里面进行使用。

2.wait: 必须暂定当前正在执行的线程,并释放资源锁,让其他线程可以有机会运行

3.notify/notifyall: 唤醒因锁池中的线程,使之运行

注意:一定要在线程同步中使用,并且是同一个锁的资源。

public class WaitNotifyDemo {

    //1.共享资源实体类
    public static class Res {
        private String userName;
        private String sex;
        private boolean flag = false;//线程间通讯标志
    }

    //2.读取线程
    public static class InThread extends Thread {

        private Res res;
        int count = 0;

        public InThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                synchronized (res){//同步加锁,解决多线程安全问题
                    if(res.flag){
                        try {
                            res.wait();//暂定当前正在执行的线程,并释放资源锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (count == 0) {
                        res.userName = "小明";
                        res.sex = "男";
                    } else {
                        res.userName = "小红";
                        res.sex = "女";
                    }
                    count = (count + 1) % 2;
                    res.flag = true;
                    res.notify();//唤醒因锁池中的线程,使之运行
                }
            }
        }
    }

    //3.写入线程
    public static class OutThread extends Thread {
        private Res res;

        public OutThread(Res res) {
            this.res = res;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                synchronized (res){//同步加锁,解决多线程安全问题
                    if(!res.flag){
                        try {
                            res.wait();//暂定当前正在执行的线程,并释放资源锁
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(res.userName + "----" + res.sex);
                    res.flag = false;
                    res.notify();//唤醒因锁池中的线程,使之运行
                }
            }
        }
    }

    public static void main(String[] args) {
        Res res = new Res();
        InThread inThread = new InThread(res);
        OutThread outThread = new OutThread(res);
        inThread.start();
        outThread.start();
    }
}

运行结果:
在这里插入图片描述

5. wait与sleep区别

  1. 对于sleep()方法,我们首先要知道该方法是属于Thread类中的。而wait()方法,则是属于Object类中的。

  2. sleep() 方法导致了程序暂停执行指定的时间,让出cpu给其他线程,但是他的监控状态依然保持者,当指定的时间到了又会自动恢复运行状态。

  3. 在调用sleep()方法的过程中,线程不会释放对象锁。

  4. 而当调用wait()方法的时候,线程会放弃对象锁,进入等待此对象的等待锁定池,只有针对此对象调用notify()方法后本线程才进入对象锁定池准备获取对象锁进入运行状态。

6. Lock锁

在 jdk1.5 之后,并发包中新增了 Lock 接口(以及相关实现类)用来实现锁功能,Lock 接口提供了与 synchronized 关键字类似的同步功能,但需要在使用时手动获取锁和释放锁。

Lock写法:

Lock lock  = new ReentrantLock();
lock.lock();
try{
	//可能会出现线程安全的操作
}finally{
	//一定在finally中释放锁
	//也不能把获取锁在try中进行,因为有可能在获取锁的时候抛出异常
  lock.ublock();
}

Lock与synchronized 关键字的区别:

  1. Lock 接口可以尝试非阻塞地获取锁 当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁。

  2. Lock 接口能被中断地获取锁 与 synchronized 不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放。

  3. Lock 接口在指定的截止时间之前获取锁,如果截止时间到了依旧无法获取锁,则返回。

7. Condition用法

Condition 的功能类似于在传统的线程技术中的,Object.wait()Object.notify()的功能。

完整代码,Lock与Condition的联和使用:

package com.ylw.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionDemo {

    //1.共享资源实体类
    public static class Res {
        private String userName;
        private String sex;
        private boolean flag = false;//线程间通讯标志
        private Lock lock = new ReentrantLock();
    }

    //2.读取线程
    public static class InThread extends Thread {

        private Res res;
        private Condition condition;
        private int count = 0;


        public InThread(Res res, Condition condition) {
            this.res = res;
            this.condition = condition;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                try {
                    res.lock.lock();
                    if(res.flag){
                        condition.await();
                    }
                    if (count == 0) {
                        res.userName = "小明";
                        res.sex = "男";
                    } else {
                        res.userName = "小红";
                        res.sex = "女";
                    }
                    count = (count + 1) % 2;
                    res.flag = true;
                    condition.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    res.lock.unlock();
                }

            }
        }
    }

    //3.写入线程
    public static class OutThread extends Thread {
        private Res res;
        private Condition condition;

        public OutThread(Res res, Condition condition) {
            this.res = res;
            this.condition = condition;
        }

        @Override
        public void run() {
            super.run();
            while (true) {
                try {
                    res.lock.lock();
                    if(!res.flag){
                        condition.await();
                    }
                    System.out.println(res.userName + "----" + res.sex);
                    res.flag = false;
                    condition.signal();

                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    res.lock.unlock();
                }

            }
        }
    }

    public static void main(String[] args) {
        Res res = new Res();
        Condition condition = res.lock.newCondition();
        InThread inThread = new InThread(res,condition);
        OutThread outThread = new OutThread(res,condition);
        inThread.start();
        outThread.start();
    }
}

总结

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_20042935/article/details/102703363