当前位置:网站首页>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();
}
}
边栏推荐
- MySQL - database query - sort query, paging query
- 华为推送服务内容,阅读笔记
- Actual combat simulation │ JWT login authentication
- 《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
- 爱可生SQLe审核工具顺利完成信通院‘SQL质量管理平台分级能力’评测
- mysql econnreset_ Nodejs socket error handling error: read econnreset
- [daily question] 1200 Minimum absolute difference
- RHCSA8
- Parsing XML using Dom4j
- Realize the addition of all numbers between 1 and number
猜你喜欢
“百度杯”CTF比赛 九月场,Web:Upload
Shu tianmeng map × Weiyan technology - Dream map database circle of friends + 1
STM32 and motor development (from architecture diagram to documentation)
潘多拉 IOT 开发板学习(HAL 库)—— 实验7 窗口看门狗实验(学习笔记)
"Baidu Cup" CTF competition in September, web:sql
MMSeg——Mutli-view时序数据检查与可视化
山东大学暑期实训一20220620
[深度学习论文笔记]UCTransNet:从transformer的通道角度重新思考U-Net中的跳跃连接
What is a network port
Pycharm installation third party library diagram
随机推荐
Pandora IOT development board learning (HAL Library) - Experiment 7 window watchdog experiment (learning notes)
Navigation property and entityset usage in SAP segw transaction code
Win10——轻量级小工具
先写API文档还是先写代码?
Flutter 绘制波浪移动动画效果,曲线和折线图
Get to know linkerd project for the first time
关于 Notion-Like 工具的反思和畅想
MSTP and eth trunk
百度杯”CTF比赛 2017 二月场,Web:爆破-2
Backup and restore of Android local SQLite database
go map
时钟周期
[深度学习论文笔记]UCTransNet:从transformer的通道角度重新思考U-Net中的跳跃连接
SAE international strategic investment geometry partner
Lb10s-asemi rectifier bridge lb10s
华为推送服务内容,阅读笔记
mysql econnreset_Nodejs 套接字报错处理 Error: read ECONNRESET
How to realize batch sending when fishing
AVC1与H264的区别
FPGA learning notes: vivado 2019.1 add IP MicroBlaze