当前位置:网站首页>Thread synchronization - producers and consumers, tortoise and rabbit race, dual thread printing
Thread synchronization - producers and consumers, tortoise and rabbit race, dual thread printing
2022-07-29 06:58:00 【A very lazy person】
This paper mainly introduces the classic case of thread synchronization and its code implementation , And explained four ways of thread synchronization , And its application in classic cases !
1. There are four ways to implement the same object lock shared by multiple threads
Scheme 1 :
- Create a thread task , To four thread objects ( There is only one thread task object , Member variable of object
( Object lock )There is only one )Option two :
- Use static Decorate the member variables that need to be shared ( This static variable
( Object lock )All objects created by this class )Option three :
- Create a utility class , It contains static member variables ( Use the class name . Variable name
( Object lock )call )
Dual thread printing is implemented in this wayOption four :
- Using constructors ( Similar to interface callback : Provide a parameterized constructor for thread tasks , When creating a thread task, pass , It can ensure that multiple thread tasks operate on the same incoming external object
( Object lock ))
Tortoise and the hare 、 Producers and consumers are realized in this way
2. Producers and consumers
- Use the synchronization method to realize thread synchronization , When creating a thread task , Using constructors ( Similar to interface callback : Provide a parameterized constructor for thread tasks , When creating a thread task, pass , It can ensure that multiple thread tasks operate on the same incoming external object
( Object lock ))- The code comments are very detailed
(1) factory ( Contains synchronization methods , It is also the following thread synchronization lock object )
public class Factory {
// The maximum number of warehouses
private final int maxNum=10;
// Current quantity of warehouse
private int currentNum=0;
// Factory production method
public synchronized void get() {
// Time to produce goods ( Block for a while )
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get producer information
String name=Thread.currentThread().getName();
// Warehouse is not full
if (currentNum<maxNum) {
// goods +1
currentNum++;
// Output production information
System.out.println(name+" Produced a commodity , The current quantity of goods in the warehouse is :"+currentNum);
// Wake up all consumers to sell , Continue to produce by yourself
this.notifyAll();
}
else {
// The warehouse is full
System.out.println(name+" Stop production ( The warehouse is full )");
// Fall into indefinite sleep , Waiting for consumers to wake up
try {
this.wait(); // Thread goes to sleep , It will not occupy lock resources ( Lock object )
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Factory consumption method
public synchronized void put() {
// Time to consume goods ( Block for a while )
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Access to consumer information
String name=Thread.currentThread().getName();
// Whether there are goods in the warehouse
if (currentNum>0) {
currentNum--;
// Output consumption information
System.out.println(name+" Sold a commodity , The current quantity of goods in the warehouse is :"+currentNum);
// Wake up consumers to produce goods
this.notifyAll();
}
else {
// The warehouse is empty
// Output information
System.out.println(name+" Stop selling ( The warehouse is empty )");
// Consumers go into indefinite sleep , Wait for the producer to wake up
try {
this.wait();// Thread to sleep , It will not occupy lock resources
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
(2) producer
public class ProductionRunnable implements Runnable{
// Guarantee to be in the same factory ( The same lock object )
private Factory factory;
// Constructors
public ProductionRunnable(Factory factory) {
// TODO Auto-generated constructor stub
this.factory=factory; // Guarantee to be in the same factory ( The same lock object )
}
@Override
public void run() {
// TODO Auto-generated method stub
// It means always producing
while(true) {
this.factory.get();
}
}
}
(3) consumer
public class SaleRunnable implements Runnable {
// Ensure the same lock object ( The same factory )
private Factory factory;
// Constructors
public SaleRunnable(Factory factory) {
// TODO Auto-generated constructor stub
this.factory=factory;
}
@Override
public void run() {
// TODO Auto-generated method stub
// Indicates that this thread has been selling
while(true) {
this.factory.put();
}
}
}
(4) Test environment
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a factory ( only one , Ensure the same lock )
Factory factory=new Factory();
// Create workers
Thread thread01=new Thread(new SaleRunnable(factory)," Xiaofang ");
Thread thread02=new Thread(new ProductionRunnable(factory)," Lao Li ");
Thread thread03=new Thread(new ProductionRunnable(factory)," Xiao Zhang ");
// Start thread , Workers work
thread01.start();
thread02.start();
thread03.start();
}
}
3. Tortoise and the hare
(1) Running ( Contains synchronization methods , It is also the following thread synchronization lock object )
public class Race {
// Rabbits run
public synchronized void rabbitRun() {
// Get thread name
String name = Thread.currentThread().getName();
for(int i=1;i<=100;i++) {
// Consume 10ms
try {
this.wait(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Print the results
if (i==81) {
// The rabbit went to sleep
try {
System.out.println(name+" fell asleep !");
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+" Wake up ");
}
System.out.println(name+" ran :"+i+" rice ");
}
System.out.println(name+" After running !");
}
// The tortoise runs
public synchronized void tortoiseRun() {
// Get thread name
String name = Thread.currentThread().getName();
for(int i=1;i<=100;i++) {
// Consume 10ms
try {
this.wait(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+" ran :"+i+" rice ");
}
// To the end , Wake up the rabbit
System.out.println(name+" After running !");
this.notifyAll();// Wake up the rabbit
}
}
(2) Rabbit thread task
public class RabbitRunnable implements Runnable {
// Definition Race Variable
private Race race;
// Constructor receives lock object
public RabbitRunnable(Race race) {
this.race=race;
}
// Call the synchronization method , The object that calls the synchronization method when locking the object
@Override
public void run() {
// TODO Auto-generated method stub
this.race.rabbitRun();
}
}
(3) Turtle thread task
public class TortoiseRunnable implements Runnable {
// Definition Race object
private Race race;
// Receive lock object
public TortoiseRunnable(Race race) {
this.race=race;
}
// Start running
@Override
public void run() {
// TODO Auto-generated method stub
this.race.tortoiseRun();
}
}
(4) Test environment
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Create a run
Race race=new Race();
// Create task object
RabbitRunnable runnable01=new RabbitRunnable(race);
TortoiseRunnable runnable02=new TortoiseRunnable(race);
// Create thread
Thread thread01=new Thread(runnable01, " The rabbit ");
Thread thread02=new Thread(runnable02, " Tortoise ");
// Start thread
thread01.start();
thread02.start();
}
}
4. Dual thread printing
Mission : Print a12b45c56…( Create two threads to print letters and numbers respectively )
The core idea : Create a utility class , It contains astatic finalDecorated objects act as locks , Then realize the continuous printing of letters and numbers
(1) Create a static lock object
public class Lock {
// Declare a lock object
public static final Object LOCK=new Object();
}
(2) Letter printing thread task
public class CharRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (Lock.LOCK) {
for(int i=97;i<=122;i++) {
// Wake up the digital process
Lock.LOCK.notifyAll();
// Print character
System.out.println((char)i);
// Go to sleep
try {
Lock.LOCK.wait(); // The thread currently using this lock enters sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// After the last letter is printed , Wake up the digital thread
Lock.LOCK.notifyAll();
}
}
}
(3) Digital print thread task
public class NumRunnable implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
synchronized (Lock.LOCK) {
for(int i=1;i<=52;i++) {
// Wake up the letter printing thread
Lock.LOCK.notifyAll();
// Print digit
System.out.println(i++);
System.out.println(i);
// Digital printing goes into sleep
try {
Lock.LOCK.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
(4) Test environment
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread thread01=new Thread(new CharRunnable());
Thread thread02=new Thread(new NumRunnable());
thread01.start();
thread02.start();
}
}
边栏推荐
- MySQL: what happens in the bufferpool when you crud? Ten pictures can make it clear
- 微信小程序的反编译
- Leetcode-1331: array ordinal conversion
- [CF1054H] Epic Convolution——数论,卷积,任意模数NTT
- 【笔记】The art of research(明白问题的重要性)
- CVPR2022Oral专题系列(一):低光增强
- Recurrent neural network RNN
- API for using the new date class of instant
- Idea cannot find a database solution
- C语言数据类型
猜你喜欢

Apisik health check test

Idea cannot find a database solution

线程 - 线程安全 - 线程优化

Sword finger offer II 115: reconstruction sequence

ECCV 2022丨轻量级模型架ParC-Net 力压苹果MobileViT代码和论文下载

Shallow reading of reentrantlock source code of abstractqueuedsynchronizer (AQS)

CDM—码分复用(简单易懂)

Ping principle

Embedding understanding + code

【冷冻电镜】Relion4.0——subtomogram教程
随机推荐
Talk about tcp/ip protocol? And the role of each layer?
How to write controller layer code gracefully?
吴恩达老师机器学习课程笔记 03 线性代数回顾
Teacher wangshuyao wrote the notes of operations research course 00 in the front
Simulation volume leetcode [normal] 081. Search rotation sort array II
leetcode-1331:数组序号转换
Teacher wangshuyao's notes on operations research 01 guidance and introduction
vscode通过remotessh结合xdebug远程调试php解决方案
Basic knowledge of MySQL (high frequency interview questions)
Mutual conversion between Base64 and file
[CF1054H] Epic Convolution——数论,卷积,任意模数NTT
游戏资产的革命
吴恩达老师机器学习课程笔记 05 Octave教程
The core of openresty and cosocket
竣达技术 | 适用于”日月元”品牌UPS微信云监控卡
Neuralcf neural collaborative filtering network
Pytorch多GPU条件下DDP集群分布训练实现(简述-从无到有)
Shallow reading of condition object source code
【冷冻电镜|论文阅读】子断层平均 M 软件解读:Multi-particle cryo-EM refinement with M
Teacher Wu Enda machine learning course notes 05 octave tutorial

