当前位置:网站首页>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();
}
}
边栏推荐
- MATLAB论文图表标准格式输出(干货)
- Rocky基础知识1
- 《2022年中国银行业RPA供应商实力矩阵分析》研究报告正式启动
- 量价虽降,商业银行结构性存款为何受上市公司所偏爱?
- Hiengine: comparable to the local cloud native memory database engine
- Flutter InkWell & Ink组件
- [daily question] 1200 Minimum absolute difference
- Android本地Sqlite数据库的备份和还原
- Could not set property ‘id‘ of ‘class XX‘ with value ‘XX‘ argument type mismatch 解决办法
- Get to know linkerd project for the first time
猜你喜欢
[深度学习论文笔记]使用多模态MR成像分割脑肿瘤的HNF-Netv2
《2022年中國銀行業RPA供應商實力矩陣分析》研究報告正式啟動
一网打尽异步神器CompletableFuture
[daily question] 1200 Minimum absolute difference
DataPipeline双料入选中国信通院2022数智化图谱、数据库发展报告
“百度杯”CTF比赛 九月场,Web:Upload
"Baidu Cup" CTF competition in September, web:upload
About the single step debugging of whether SAP ui5 floating footer is displayed or not and the benefits of using SAP ui5
Write macro with word
蜀天梦图×微言科技丨达梦图数据库朋友圈+1
随机推荐
jenkins安装
Flutter draws animation effects of wave movement, curves and line graphs
国际自动机工程师学会(SAE International)战略投资几何伙伴
Word document injection (tracking word documents) incomplete
Detailed explanation of navigation component of openharmony application development
MSTP and eth trunk
Go string operation
ASEMI整流桥HD06参数,HD06图片,HD06应用
数据泄露怎么办?'华生·K'7招消灭安全威胁
About the single step debugging of whether SAP ui5 floating footer is displayed or not and the benefits of using SAP ui5
Halcon template matching actual code (I)
MySQL splits strings for conditional queries
Backup and restore of Android local SQLite database
Binder communication process and servicemanager creation process
The Research Report "2022 RPA supplier strength matrix analysis of China's banking industry" was officially launched
【每日一题】1200. 最小绝对差
go 指针
RHCSA9
The solution of outputting 64 bits from printf format%lld of cross platform (32bit and 64bit)
[深度学习论文笔记]TransBTSV2: Wider Instead of Deeper Transformer for Medical Image Segmentation