目录

知识点1:多线程之间如何实现通讯

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

2、多线程之间通讯需求

3、代码实现基本实现

(1)共享资源源实体类

(2)输入线程资源

(3)输出线程

(4)运行代码

(5)解决线程安全问题

知识点2:wait、notify方法

知识点3:wait与sleep区别

知识点4:Lock锁

1、Lock写法

2、Lock与synchronized 关键字的区别

3、Condition用法


知识点1:多线程之间如何实现通讯

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

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

画图演示

2、多线程之间通讯需求

需求:第一个线程写入(input)用户,另一个线程取读取(out)用户.实现读一个,写一个操作。

3、代码实现基本实现

(1)共享资源源实体类

class Res {public String userSex;public String userName;
}

(2)输入线程资源

class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {if (count == 0) {res.userName = "余胜军";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;}}
}

(3)输出线程

class OutThread extends Thread {private Res res;public OutThread(Res res) {this.res = res;}@Overridepublic void run() {while (true) {System.out.println(res.userName + "--" + res.userSex);}}
}

(4)运行代码

Res res = new Res();
IntThrad intThrad = new IntThrad(res);
OutThread outThread = new OutThread(res);
intThrad.start();
outThread.start();

(5)解决线程安全问题

IntThrad 加上synchronized

class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (count == 0) {res.userName = "余胜军";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;}}}
}

输出线程加上synchronized

class Res {public String userName;public String sex;
}class InputThread extends Thread {private Res res;public InputThread(Res res) {this.res = res;}@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (count == 0) {res.userName = "余胜军";res.sex = "男";} else {res.userName = "小红";res.sex = "女";}count = (count + 1) % 2;}}}
}class OutThrad extends Thread {private Res res;public OutThrad(Res res) {this.res = res;}@Overridepublic void run() {while (true) {synchronized (res) {System.out.println(res.userName + "," + res.sex);}}}
}public class ThreadDemo01 {public static void main(String[] args) {Res res = new Res();InputThread inputThread = new InputThread(res);OutThrad outThrad = new OutThrad(res);inputThread.start();outThrad.start();}}

知识点2:wait、notify方法

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

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

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

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

class Res {public String userSex;public String userName;//线程通讯标识public boolean flag = false;
}
class IntThrad extends Thread {private Res res;public IntThrad(Res res) {this.res = res;        }@Overridepublic void run() {int count = 0;while (true) {synchronized (res) {if (res.flag) {try {// 当前线程变为等待,但是可以释放锁res.wait();} catch (Exception e) {}}if (count == 0) {res.userName = "余胜军";res.userSex = "男";} else {res.userName = "小紅";res.userSex = "女";}count = (count + 1) % 2;res.flag = true;// 唤醒当前线程res.notify();}}}
}
class OutThread extends Thread {private Res res;public OutThread(Res res) {this.res = res;}@Overridepublic void run() {while (true) {synchronized (res) {if (!res.flag) {try {res.wait();} catch (Exception e) {// TODO: handle exception}}System.out.println(res.userName + "--" + res.userSex);res.flag = false;res.notify();}}}
}
public class ThreaCommun {public static void main(String[] args) {Res res = new Res();IntThrad intThrad = new IntThrad(res);OutThread outThread = new OutThread(res);intThrad.start();outThread.start();}
}

知识点3:wait与sleep区别

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

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

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

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


知识点4:Lock锁

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

1、Lock写法

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

2、Lock与synchronized 关键字的区别

Lock 接口可以尝试非阻塞地获取锁 当前线程尝试获取锁。如果这一时刻锁没有被其他线程获取到,则成功获取并持有锁。
Lock 接口能被中断地获取锁 与 synchronized 不同,获取到锁的线程能够响应中断,当获取到的锁的线程被中断时,中断异常将会被抛出,同时锁会被释放。

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

3、Condition用法

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

Condition condition = lock.newCondition();
res. condition.await();  类似wait
res. Condition. Signal() 类似notify
class Res {public String userName;public String sex;public boolean flag = false;Lock lock = new ReentrantLock();
}class InputThread extends Thread {private Res res;Condition newCondition;public InputThread(Res res,   Condition newCondition) {this.res = res;this.newCondition=newCondition;}@Overridepublic void run() {int count = 0;while (true) {// synchronized (res) {try {res.lock.lock();if (res.flag) {try {
//                      res.wait();newCondition.await();} catch (Exception e) {// TODO: handle exception}}if (count == 0) {res.userName = "余胜军";res.sex = "男";} else {res.userName = "小红";res.sex = "女";}count = (count + 1) % 2;res.flag = true;
//              res.notify();newCondition.signal();} catch (Exception e) {// TODO: handle exception}finally {res.lock.unlock();}}// }}
}class OutThrad extends Thread {private Res res;private Condition newCondition;public OutThrad(Res res,Condition newCondition) {this.res = res;this.newCondition=newCondition;}@Overridepublic void run() {while (true) {
//          synchronized (res) {try {res.lock.lock();if (!res.flag) {try {
//                      res.wait();newCondition.await();} catch (Exception e) {// TODO: handle exception}}System.out.println(res.userName + "," + res.sex);res.flag = false;
//              res.notify();newCondition.signal();} catch (Exception e) {// TODO: handle exception}finally {res.lock.unlock();}
//          }}}
}public class ThreadDemo01 {public static void main(String[] args) {Res res = new Res();Condition newCondition = res.lock.newCondition();InputThread inputThread = new InputThread(res,newCondition);OutThrad outThrad = new OutThrad(res,newCondition);inputThread.start();outThrad.start();}}

【4】多线程之间实现通讯相关推荐

  1. java多线程有几种实现方法_Java多线程之间实现通讯

    一.课程目标 多线程之间如何通讯 wait.notify.notifyAll()方法 lock 停止线程 守护线程 Join方法 优先级 Yield 二.多线程之间如何实现通讯 2.1 什么是多线程之 ...

  2. java多线程间的通讯

    什么是多线程之间的通讯? 就是多个线程在操作同一个资源,但是操作的动作不同. package com;class Printer{// 打印机public String fileName;public ...

  3. Java 多线程之间通讯(面试概念解答三)

    多线程之间通讯 多线程之间如何实现通讯? wait().notify.notifyAll()方法 wait与sleep区别? JDK1.5-Lock Lock 接口与 synchronized 关键字 ...

  4. 多线程Synchronized锁的使用与线程之间的通讯

    多线程Synchronized锁的使用与线程之间的通讯 一.什么是线程安全问题 二.如何解决线程安全问题 三.synchronized锁的基本用法 1.修饰代码块(this锁) 2.修饰实例方法(th ...

  5. 不用编程,实现三菱FX5U与罗克韦尔(AB)PLC之间实时通讯

    IGT-DSER智能网关模块支持西门子.三菱.欧姆龙.AB等各种品牌的PLC之间通讯,同时也支持PLC与Modbus协议的工业机器人.智能仪表等设备通讯.网关有多个网口.串口,也可选择WIFI,4G无 ...

  6. C++多线程之间,线程函数启动之后,多线程依赖的启动和线程唤醒操作。

    C++多线程之间,线程函数启动之后,线程间依赖的启动和唤醒操作 一.原理分析 1. 线程依赖关系 二. 实例分析 2.1 多线程启动 2.2 多线程模式讲解 (1) 多线程开启与主线程唤醒 (2)单线 ...

  7. django两个服务器之间的通讯

    django两个服务器之间的通讯 ajax通讯 服务器127.0.0.1:8000的代码如下: /project/project/urls: from django.contrib import ad ...

  8. 非常详细的测试unity与android之间的通讯操作

    非常详细的测试unity与android之间的通讯操作 博客分类: unity3dandroid 非常详细的测试unity与android之间的通讯操作 转载自 http://www.narkii.c ...

  9. python 线程等待_详解python多线程之间的同步(一)

    引言: 线程之间经常需要协同工作,通过某种技术,让一个线程访问某些数据时,其它线程不能访问这些数据,直到该线程完成对数据的操作.这些技术包括临界区(Critical Section),互斥量(Mute ...

最新文章

  1. 零基础学习python爬虫_教你零基础如何入门Python爬虫!
  2. GCC 警告选项 -Werror
  3. Forward+ Shading架构
  4. python多久学会自学-怎么自学python,大概要多久?
  5. Linux问题分析或解决_samba无法连接
  6. 安装 PyTorch C++ API libtorch 及一个最小例子
  7. python是开源工具吗_微软最强 Python 自动化工具开源了!不用写一行代码
  8. java性能分析工具_java性能分析工具
  9. 深入理解磁盘文件系统之inode
  10. 第 8 章 TokyoCabinet/Tyrant
  11. android textview显示表情,在Android TextView中显示表情符号/情感图标
  12. 超大数据量操作 java程序优化[转载]
  13. 远程删除用户照片?刚刚,拼多多承认了!
  14. 2015年10月22日22:38:46
  15. 关于jQuery、AJAX、JSON(一)
  16. FPGA智能网卡-HairPin功能
  17. USTC2017 writeup
  18. 38译码器数码管c语言代码,51单片机38译码器实现动态数码管控制
  19. 思维导图怎么制作?这些制作技巧,支持一键模板套用,建议收藏
  20. C语言自学指南(总觉 光阴不够)

热门文章

  1. 自然语言处理:词性标注
  2. 如何清除计算机搜索框内的搜索历史记录,win10系统删除搜索框历史记录的操作方法...
  3. 2001年考研数学一真题pdf
  4. 软件工程作业--评价自己经常使用的输入法
  5. 每日分享:可以将文字转换成语音的软件有哪些?
  6. 为什么电信通信电压通常为负电压-48V?
  7. 强化学习在阿里广告排序和竞价中的应用
  8. 中文 NLP 工具总结
  9. thrift传值问题
  10. 澳门大学计算机语言博士生导师王珊,博士招生 | 澳门大学王珊招收语言学等方向学生...