当前位置:网站首页>4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
4 years of working experience, and you can't tell the five communication modes between multithreads. Can you believe it?
2022-06-29 07:42:00 【xy29981】

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();
}
}
Based on the idea of microservice , Builds on the B2C Project practice in e-commerce scenario . Core technology stack , yes Spring Boot + Dubbo . future , It reconstructs Spring Cloud Alibaba .
Project address :https://github.com/YunaiV/onemall
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 .
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();
}
}
Please look forward to my next article , thank you .

more java Advanced information , Interview information , Official account
边栏推荐
- IMX6DL4.1.15支持EIM总线(上)——实际操作,修改内容。
- Final summary spark
- 358. K distance interval rearrange string sorting
- 虚拟DOM真的是最快的吗?
- 节流的两种写法-最近看到的这种写法
- 蓝桥杯——13届第二批试题解析
- Blue Bridge Cup -- Analysis of the second batch of test questions of the 13th session
- 项目中 if else 的代替写法
- 循环嵌套问题:为什么大循环在内,小循环在外可以提高程序的运行效率
- Matlab Simulink simulation and analysis of power grid sweep frequency
猜你喜欢

IMX6DL4.1.15支持EIM总线(上)——实际操作,修改内容。

阿里云访问资源:NoSuchKey

KingbaseES V8R6集群维护案例之--单实例数据迁移到集群案例

tf.count_nonzero
![[FreeRTOS] interrupt mechanism](/img/ab/9b1d07048b4631d7cc95db99ed529a.png)
[FreeRTOS] interrupt mechanism

Autosar SWC在Simulink中Parameter的使用

matlab 多普勒效应产生振动信号和处理

Kyushu cloud helps Inner Mongolia's "counting from the east to the west" project to drive the smart new ecology of the surveying and mapping industry

【工控老马】单片机与西门子S7-200通信原理详解

九州云助力内蒙古“东数西算”工程,驱动测绘行业智慧新生态
随机推荐
tf. compat. v1.assign
What is a Test Architect
服裝行業的CRM品牌供應商如何選型?
SQL 注入绕过(六)
Use of parameter in Simulink for AUTOSAR SWC
机器学习笔记 - 时间序列的混合模型
What you should know about databases
tf. compat. v1.global_ variables
游标长时间open导致表无法vacuum问题
Markdown skill tree (2): paragraph and emphasis
cv::Mat与Base64转换(含图片压缩解压等流程)
Deploy Prometheus server service system management
Alternative writing of if else in a project
Markdown skill tree (7): separator and reference
Appium automation test foundation ADB common commands (III)
1032 Sharing
施努卡:3d视觉检测方案 3d视觉检测应用行业
[popular science materials] materials from scientific spirit to scientific knowledge
测试人员需要了解的工具有哪些
excel高级绘图技巧100讲(六)-甘特图在项目进度上的实战应用案例