当前位置:网站首页>Fixed and alternate sequential execution of modes
Fixed and alternate sequential execution of modes
2022-07-25 23:50:00 【Sit in the sunny window and drink tea alone】
Execute in a fixed sequence
wait && notify
The basic idea :
- Threads t1 Loop waiting thread t2 End of execution condition
- Threads t2 Print 2, Then wake up wait The thread of
package cn.knightzz.partten;
import lombok.extern.slf4j.Slf4j;
/** * @author Wang Tianci * @title: TestAsyncModePrint * @projectName hm-juc-codes * @description: Synchronous printing of sequence control * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-07-24 13:38 */
@SuppressWarnings("all")
@Slf4j(topic = "c.TestAsyncModePrint")
public class TestAsyncModePrint {
// The basic idea :
// 1. Threads t1 Loop waiting thread t2 End of execution condition
// 2. Threads t2 Print 2, Then wake up wait The thread of
private static Object lock = new Object();
private static boolean isFinish = true;
public static void main(String[] args) {
// Fixed order , You must print 2 Re print 1
Thread t1 = new Thread(() -> {
synchronized (lock) {
while (!isFinish) {
try {
// wait The thread will release the lock
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
log.debug("print 1");
}
}, "t1");
t1.start();
Thread t2 = new Thread(() -> {
log.debug("print 2");
synchronized (lock) {
// Modify the execution flag , Wake up all threads
isFinish = true;
// Wake up other threads , Let other counties enter EntryList , Waiting for lock
// t2 The lock will also be released after execution
lock.notifyAll();
}
}, "t2");
t2.start();
}
}

Park && unPark
You can see , Implementation is troublesome :
- First , We need to make sure that wait Again notify, otherwise wait The thread will never wake up . So it USES 『 Run flag 』 To decide whether to wait
- second , If the thread interferes with some errors notify 了 wait Threads , Wait again when the conditions are not met , Used while Cycle to solve This problem
- Last , Wake up... On the object wait Threads need to use notifyAll, because 『 Synchronize objects 』 There may be more than one waiting thread on the
package cn.knightzz.partten;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.LockSupport;
/** * @author Wang Tianci * @title: TestAsyncModePrint * @projectName hm-juc-codes * @description: Synchronous printing of sequence control * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-07-24 13:38 */
@SuppressWarnings("all")
@Slf4j(topic = "c.TestAsyncModePrintPark")
public class TestAsyncModePrintPark {
// The basic idea :
// 1. Threads t1 Loop waiting thread t2 End of execution condition
// 2. Threads t2 Print 2, Then wake up wait The thread of
private static Object lock = new Object();
public static void main(String[] args) {
// Fixed order , You must print 2 Re print 1
Thread t1 = new Thread(() -> {
// Waiting for License
LockSupport.park();
log.debug("print 1");
}, "t1");
t1.start();
Thread t2 = new Thread(() -> {
log.debug("print 2");
// to t1 Issue licenses ,( Multiple consecutive calls unpark Only one... Will be issued 『 The license 』)
LockSupport.unpark(t1);
}, "t2");
t2.start();
}
}

park and unpark The method is more flexible , Which of them calls first , It doesn't matter who calls later. . And it is carried out in the unit of thread 『 Pause 』 And recovery , Unwanted Synchronize objects and Run flag
Alternate execution
wait && notify
The basic idea
- You need to define a class to store flag and Number of times to print
- If we want to print a b c , that flag That's it 1 2 3
- Circular judgement flag Whether the conditions are met , If you are not satisfied, just wait , Print after meeting the conditions
- Then set the flag = nextFlag , Then wake up other threads
- All threads share the same Class object
Code implementation
package cn.knightzz.partten;
import lombok.extern.slf4j.Slf4j;
/** * @author Wang Tianci * @title: TestAlterPrintWait * @projectName hm-juc-codes * @description: Use wait&¬ify Alternate printing * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-07-24 15:18 */
@SuppressWarnings("all")
@Slf4j(topic = "c.TestAsyncModePrintPark")
public class TestAlterPrintWait {
// The basic idea :
// 1. Set an integer marker bit , Suppose the thread is 3 individual t1 => 1, t2 ==> 2 , t3 ==> 3
// Print if the conditions are met , If you are not satisfied, cycle
// 2. Set up nextFlag, Used to set the mark bit of the next print
public static void main(String[] args) {
WaitNotify waitNotify = new WaitNotify(1, 5);
new Thread(() -> {
waitNotify.print(1, 2, "a");
}, "t1").start();
new Thread(() -> {
waitNotify.print(2, 3, "b");
}, "t2").start();
new Thread(() -> {
waitNotify.print(3, 1, "c");
}, "t3").start();
}
}
@SuppressWarnings("all")
class WaitNotify {
// Wait for the marker bit
private int flag;
// Set the number of cycles
private int loopNumber;
public WaitNotify(int flag, int loopNumber) {
this.flag = flag;
this.loopNumber = loopNumber;
}
/** * Print information , Requirement realization abcabcabc This effect * * @param waitFlag Wait condition flag bit * @param nextFlag Next printed marker bit * @param str Printed information */
public void print(int waitFlag, int nextFlag, String str) {
for (int i = 0; i < loopNumber; i++) {
synchronized (this) {
// Judge whether the current flag bit meets the conditions
while (waitFlag != flag) {
// Wait until you meet the conditions
try {
this.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
// Print information when conditions are met
System.out.println("str = " + str);
// Set the next marker bit
this.flag = nextFlag;
// Wakes up other threads
this.notifyAll();
}
}
}
}
lock Condition variables,
The basic idea
- Definition waitSingal Class inheritance ReentrantLock
- By defining different Condition object , Let different threads in the corresponding WaitSet Waiting inside .
- After the current thread finishes executing , Release the lock , Then wake up the next thread
Code implementation
package cn.knightzz.partten;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/** * @author Wang Tianci * @title: TestAlterPrintLock * @projectName hm-juc-codes * @description: Use Lock Realize alternate printing * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-07-25 07:32 */
@SuppressWarnings("all")
@Slf4j(topic = "c.TestAlterPrintLock")
public class TestAlterPrintLock {
public static void main(String[] args) throws InterruptedException {
AwaitSignal awaitSignal = new AwaitSignal(5);
// Create different waiting queues
Condition conditionA = awaitSignal.newCondition();
Condition conditionB = awaitSignal.newCondition();
Condition conditionC = awaitSignal.newCondition();
new Thread(() -> {
awaitSignal.print("a", conditionA, conditionB);
}, "t1").start();
new Thread(() -> {
awaitSignal.print("b", conditionB, conditionC);
}, "t2").start();
new Thread(() -> {
awaitSignal.print("c", conditionC, conditionA);
}, "t3").start();
// sleep 1s
TimeUnit.SECONDS.sleep(1);
// The main thread obtains the lock first , Even if other threads get the lock first , Will also directly await(), When waiting, you will enter the corresponding Condition, Then release the lock
awaitSignal.lock();
log.debug("==============================================");
log.debug(" The main thread obtains the lock first , Even if other threads get the lock first , Will also directly await(), When waiting, you will enter the corresponding Condition, Then release the lock ");
log.debug("==============================================");
try {
// Wakeup condition A Threads
log.debug(" Start ... ");
conditionA.signal();
}finally {
awaitSignal.unlock();
}
}
}
@SuppressWarnings("all")
@Slf4j(topic = "c.AwaitSignal")
class AwaitSignal extends ReentrantLock {
private int loopNumber;
public AwaitSignal(int loopNumber) {
this.loopNumber = loopNumber;
}
public void print(String info, Condition current, Condition next) {
for (int i = 0; i < loopNumber; i++) {
// Get the lock , The function of lock is to ensure atomicity , Lock acquisition cycle , The code can be executed completely , Instead of switching thread context
this.lock();
log.debug(" Lock acquired successfully !");
try {
// The current thread is waiting
log.debug(" The current thread is waiting !");
current.await();
log.debug(" Wait for the end of printing info!");
// Wait for the end of printing info
log.debug(" info = {}", info);
// Wake up the next Condition The thread of
log.debug(" Wake up the next Condition The thread of !");
next.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
// Release the lock
this.unlock();
}
}
}
}

park && unpark
The basic idea
- The idea is simple , Define a SyncPark class , Define a Thread Array objects threads, Then used to store threads
- When getting the next thread , Will traverse threads , And then use
LockSupport.unpark(next);
Code implementation
package cn.knightzz.partten;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.locks.LockSupport;
/** * @author Wang Tianci * @title: TestAlterPrintPark * @projectName hm-juc-codes * @description: Use Park&&UnPark Alternate printing * @website <a href="http://knightzz.cn/">http://knightzz.cn/</a> * @github <a href="https://github.com/knightzz1998">https://github.com/knightzz1998</a> * @create: 2022-07-25 09:05 */
@SuppressWarnings("all")
@Slf4j(topic = "c.TestAlterPrintPark")
public class TestAlterPrintPark {
public static void main(String[] args) {
SyncPark syncPark = new SyncPark(5);
Thread t1 = new Thread(() -> {
syncPark.print("a");
}, "t1");
Thread t2 = new Thread(() -> {
syncPark.print("b");
}, "t2");
Thread t3 = new Thread(() -> {
syncPark.print("c");
}, "t3");
syncPark.setThreads(t1, t2, t3);
syncPark.start();
}
}
@Slf4j(topic = "c.SyncPark")
@SuppressWarnings("all")
class SyncPark {
private int loopNumber;
private Thread[] threads;
public SyncPark(int loopNumber) {
this.loopNumber = loopNumber;
}
public void setThreads(Thread... threads) {
this.threads = threads;
}
public void print(String info) {
for (int i = 0; i < loopNumber; i++) {
// Get the lock
LockSupport.park();
// Print
log.debug("info = {} ", info);
// Release the lock
Thread next = nextThread();
LockSupport.unpark(next);
}
}
public Thread nextThread() {
// Get the current thread
Thread current = Thread.currentThread();
int index = 0;
// Traverse the thread array , Find the current thread
for (int i = 0; i < threads.length; i++) {
if (threads[i] == current) {
index = i;
break;
}
}
if (index < threads.length - 1) {
return threads[index + 1];
} else {
return threads[0];
}
}
public void start() {
for (Thread thread : threads) {
thread.start();
}
// Release voucher
LockSupport.unpark(threads[0]);
}
}

边栏推荐
- QT smart pointer error prone point
- A long detailed explanation of C language operators
- Taobao Search case
- 《数据密集型应用系统设计》 - 应用系统概览
- Topsis与熵权法
- [intelligence question] interview intelligence question
- Call nailing API and report an error: the signature sent by the robot is expired; Solution: please keep the signature generation time and sending time within timestampms
- 反射之类加载过程
- 热部署和热加载有什么区别?
- 模式之固定与交替顺序执行
猜你喜欢

This point inside the function / change this point inside the function

C language implementation of three chess

Duplicate numbers in array

开放API生态系统面临的十个威胁

ES6 syntax (difference between let, const, VaR, deconstruction assignment, arrow function, residual parameters, extension method of array)
![[JUC] concurrent keyword volatile](/img/80/2f1b33f1e8c87fd4f8806eafb83139.png)
[JUC] concurrent keyword volatile

Generating random number random learning uniform_ int_ distribution,uniform_ real_ distribution

numeric学习之iota,accumulate

图的遍历-DFS,BFS(代码详解)

Storage of data in memory
随机推荐
Ratio of learning_ add,ratio_ subtract,ratio_ multiply,ratio_ Use of divide
Part 67: conversion between keypoint and point2f in opencv
反射之类加载过程
Release of v6.5.1/2/3 series of versions of Xingyun housekeeper: the ability of database OpenAPI continues to be strengthened
下一代终端安全管理的关键特征与应用趋势
[debug bug] JS: getFullYear is not a function
The expression of flag=false if (flag) {return} timer=null if (timer) {return} in the throttle valve has been unclear
死信队列 和消息TTL过期代码
ABAP 代码中读取会计科目的字段状态(隐藏、可选、必输)
[nodejs] nodejs create a simple server
LeetCode 0919. 完全二叉树插入器:完全二叉树的数组表示
LeetCode 0135. 分发糖果
1913. 两个数对之间的最大乘积差-无需排序法
2022-07-18 study notes of group 5 self-cultivation class (every day)
VSCode格式化Json文件
十大排序之快速排序
SAP Message No. VG202 IDoc E1EDK18 中付款条款已经转移:检查数据
R language installation tutorial | graphic introduction is super detailed
Demo of pointer function
Function definition and call