当前位置:网站首页>With 4 years of working experience, you can't tell five ways of communication between multithreads. Dare you believe it?
With 4 years of working experience, you can't tell five ways of communication between multithreads. Dare you believe it?
2022-07-05 13:21:00 【Luo Hanxiang】
problem
There are two threads ,A Threads add elements to a collection in turn “abc” character string , A total of ten times , When added to the fifth time , hope B The thread can receive A Thread notification , then B Threads perform related business operations . There are two models of inter thread communication : Shared memory and messaging , The following methods are implemented based on these two models .
One 、 Use volatile keyword
be based on volatile Keyword to achieve communication between threads is the idea of using shared memory . It means that multiple threads listen to a variable at the same time , When this variable changes , Threads can sense and execute the corresponding business . It's also the simplest way to do it
public class TestSync {
// Define shared variables for communication , It needs to volatile modification , Otherwise, the thread cannot perceive in time
static volatile boolean notice = false;
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// Threads A
Thread threadA = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
list.add("abc");
System.out.println(" Threads A Additive elements , here list Of size by :" + list.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (list.size() == 5)
notice = true;
}
});
// Threads B
Thread threadB = new Thread(() -> {
while (true) {
if (notice) {
System.out.println(" Threads B Receive notice , Start your own business ...");
break;
}
}
});
// You need to start the thread first B
threadB.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Restart thread A
threadA.start();
}
}
Two 、 Use Object Class wait()/notify()
Object Class provides a way to communicate between threads :wait()
、notify()
、notifyAll()
, They are the basis of multithreading communication , The idea of this way of implementation is naturally the communication between threads .
Be careful :wait/notify
Must cooperate synchronized
Use ,wait Method release lock ,notify Method does not release the lock .wait In a thread that has entered a synchronization lock , Let yourself out of sync lock temporarily , So that other threads waiting for this lock can get the synchronization lock and run , Only other threads called notify()
,notify Do not release lock , Just told me that it was called wait()
Threads of can participate in the competition for locks , But not immediately , Because the lock is still in someone's hands , Others haven't released , call wait()
One or more threads of the will be released wait state , Re participate in the competition , If the program can get the lock again , You can continue to run down .
public class TestSync {
public static void main(String[] args) {
// Define a lock object
Object lock = new Object();
List<String> list = new ArrayList<>();
// Threads A
Thread threadA = new Thread(() -> {
synchronized (lock) {
for (int i = 1; i <= 10; i++) {
list.add("abc");
System.out.println(" Threads A Additive elements , here list Of size by :" + list.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (list.size() == 5)
lock.notify();// Wake up the B Threads
}
}
});
// Threads B
Thread threadB = new Thread(() -> {
while (true) {
synchronized (lock) {
if (list.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" Threads B Receive notice , Start your own business ...");
}
}
});
// You need to start the thread first B
threadB.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Restart thread A
threadA.start();
}
}
From the output , In a thread A issue notify()
After wake-up notification , It's still after you finish your own thread business , Threads B Just started to execute , Just explain notify()
No release lock , and wait()
Release the lock .
wait() and notify() All are Object Class , Be careful. ,wait and notify It has to go with synchronized Use , also notify() It won't release the lock
public class SynchronizedTest {
// Define a year, Used to record the practice years of a star
private static double year;
public void run() {
// Threads A, Practice singing and dancing rap
Thread threadA = new Thread(() -> {
synchronized (this) {
for (year = 0.5; year <= 5; year += 0.5) {
System.out.println(" Cai Xuji began to practice singing and dancing rap: Practiced " + year + " year ");
try {
Thread.sleep(288);
} catch (InterruptedException e) {
e.printStackTrace();
}
// as everyone knows , Practice for two and a half years to get out
if (year == 2.5) {
System.out.println("===========================> Two and a half years of successful practice , career !!!");
this.notify();
}
}
}
});
// Threads B, Practice playing basketball
Thread threadB = new Thread(() -> {
while (true) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" Cai Xuji began to practice playing basketball ");
}
}
});
// Be careful , Be sure to start first B, Otherwise it will lead to B Never get the lock
threadB.start();
threadA.start();
}
public static void main(String[] args) {
SynchronizedTest test = new SynchronizedTest();
test.run();
}
}
3、 ... and 、 Use JUC Tool class CountDownLatch
jdk1.5 After the java.util.concurrent
The package provides many tool classes related to concurrent programming , It simplifies the writing of concurrent programming code ,CountDownLatch
be based on AQS frame , This is equivalent to maintaining a shared variable between threads state.
public class TestSync {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(1);
List<String> list = new ArrayList<>();
// Threads A
Thread threadA = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
list.add("abc");
System.out.println(" Threads A Additive elements , here list Of size by :" + list.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (list.size() == 5)
countDownLatch.countDown();
}
});
// Threads B
Thread threadB = new Thread(() -> {
while (true) {
if (list.size() != 5) {
try {
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" Threads B Receive notice , Start your own business ...");
break;
}
});
// You need to start the thread first B
threadB.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Restart thread A
threadA.start();
}
}
Four 、 Use ReentrantLock combination Condition
public class TestSync {
public static void main(String[] args) {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
List<String> list = new ArrayList<>();
// Threads A
Thread threadA = new Thread(() -> {
lock.lock();
for (int i = 1; i <= 10; i++) {
list.add("abc");
System.out.println(" Threads A Additive elements , here list Of size by :" + list.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (list.size() == 5)
condition.signal();
}
lock.unlock();
});
// Threads B
Thread threadB = new Thread(() -> {
lock.lock();
if (list.size() != 5) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" Threads B Receive notice , Start your own business ...");
lock.unlock();
});
threadB.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadA.start();
}
}
This method is not very good to use , The code is complex , And threads B In being A After waking up, it cannot be executed immediately because the lock is not obtained , in other words ,A After wake-up operation , Do not release lock . This method follows Object Of wait()/notify()
equally .
5、 ... and 、 basic LockSupport Realize the blocking and wake-up between threads
LockSupport
It is a very flexible tool to implement inter thread blocking and wakeup , It doesn't need to focus on whether to wait for the thread to run first or wake up the thread to run first , But you need to know the name of the thread .
public class TestSync {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
// Threads B
final Thread threadB = new Thread(() -> {
if (list.size() != 5) {
LockSupport.park();
}
System.out.println(" Threads B Receive notice , Start your own business ...");
});
// Threads A
Thread threadA = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
list.add("abc");
System.out.println(" Threads A Additive elements , here list Of size by :" + list.size());
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (list.size() == 5)
LockSupport.unpark(threadB);
}
});
threadA.start();
threadB.start();
}
}
边栏推荐
- Default parameters of function & multiple methods of function parameters
- AVC1与H264的区别
- Hundred days to complete the open source task of the domestic database opengauss -- openguass minimalist version 3.0.0 installation tutorial
- 数据泄露怎么办?'华生·K'7招消灭安全威胁
- 【Hot100】33. Search rotation sort array
- FPGA learning notes: vivado 2019.1 add IP MicroBlaze
- 【服务器数据恢复】某品牌服务器存储raid5数据恢复案例
- 精彩速递|腾讯云数据库6月刊
- Simple page request and parsing cases
- restTemplate详解
猜你喜欢
碎片化知识管理工具Memos
ABAP editor in SAP segw transaction code
FPGA 学习笔记:Vivado 2019.1 添加 IP MicroBlaze
Le rapport de recherche sur l'analyse matricielle de la Force des fournisseurs de RPA dans le secteur bancaire chinois en 2022 a été officiellement lancé.
About the single step debugging of whether SAP ui5 floating footer is displayed or not and the benefits of using SAP ui5
Principle and performance analysis of lepton lossless compression
Pycharm installation third party library diagram
Hiengine: comparable to the local cloud native memory database engine
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
一文详解ASCII码,Unicode与utf-8
随机推荐
How to realize batch sending when fishing
There is no monitoring and no operation and maintenance. The following is the commonly used script monitoring in monitoring
leetcode:221. Maximum square [essence of DP state transition]
Hundred days to complete the open source task of the domestic database opengauss -- openguass minimalist version 3.0.0 installation tutorial
Binder通信过程及ServiceManager创建过程
Backup and restore of Android local SQLite database
Notion 类笔记软件如何选择?Notion 、FlowUs 、Wolai 对比评测
FPGA 学习笔记:Vivado 2019.1 添加 IP MicroBlaze
Matlab paper chart standard format output (dry goods)
[深度学习论文笔记]UCTransNet:从transformer的通道角度重新思考U-Net中的跳跃连接
Reverse Polish notation
go 指针
go 数组与切片
同事半个月都没搞懂selenium,我半个小时就给他整明白!顺手秀了一波爬淘宝的操作[通俗易懂]
OpenHarmony应用开发之Navigation组件详解
Integer ==比较会自动拆箱 该变量不能赋值为空
事务的基本特性和隔离级别
STM32 and motor development (from architecture diagram to documentation)
蜀天梦图×微言科技丨达梦图数据库朋友圈+1
Difference between avc1 and H264