当前位置:网站首页>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
边栏推荐
- 服裝行業的CRM品牌供應商如何選型?
- Imx6dl4.1.15 supports EIM bus (upper) - actual operation and modification.
- 关于开发web场景下如何解决手机访问web跨域问题
- Appium automation test foundation ADB common commands (III)
- 施努卡:什么是视觉定位系统 视觉定位系统的工作原理
- 1183: patient queue
- Concurrent idempotent anti shake
- 软件测试鸾音鹤信
- MFC中利用CDockablePane实现悬浮窗
- 【工控老马】基于西门子S7-200PLC的跑马灯控制系统的设计方案详解
猜你喜欢

cv2.cvtColor

SQL 注入绕过(六)

Concurrent idempotent anti shake

施努卡:3d机器视觉检测系统 3d视觉检测应用行业

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

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

【工控老马】洗衣机PLC程序控制系统设计详解

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

100 lectures on Excel advanced drawing skills (VI) - practical application cases of Gantt chart in project progress

Swin Transformer理论讲解
随机推荐
Simulation analysis of sailing dynamics
tf.to_int64
How to view software testing training? Do you need training?
蓝桥杯——13届第二批试题解析
Markdown skill tree (6): List
游标长时间open导致表无法vacuum问题
Check whether tensorflow supports GPU and test program
[translation] swarmed out. Design methods for building modern applications
阿里云访问资源:NoSuchKey
Markdown skill tree (9): tables
100 lectures on Excel advanced drawing skills (VI) - practical application cases of Gantt chart in project progress
Appium 环境搭建
软件测试鸾音鹤信
解题-->在线OJ(十三)
Suggestions on working methods and efficient work
Roblox剑九之剑二
Schnuka: 3D machine vision inspection system 3D vision inspection application industry
mmclassification安装与调试
IMX6DL4.1.15支持EIM总线(下)——配置原理分析。
excel高级绘图技巧100讲(六)-甘特图在项目进度上的实战应用案例