当前位置:网站首页>[interview: concurrent Part 24: multithreading: comprehensive exercise] sequence control
[interview: concurrent Part 24: multithreading: comprehensive exercise] sequence control
2022-07-25 21:29:00 【I cream】
【 interview : Concurrent articles 24: Multithreading : Comprehensive practice 】 Sequence control
00. Preface
If you have any questions, please point out , thank .
01. Introduce
We ask two questions Use them separately wait/notify,park/unpark,await/signal solve .
02. Question 1
Introduce
We create two threads from 1 Alternate print to 10
wait/notify Realization
@Slf4j(topic = "c.TestSun")
public class TestSun {
public static void main(String[] args) {
// Print five rounds alternately
TestNumber num = new TestNumber(5);
new Thread(()->{
num.print(true);
},"t1").start();
new Thread(()->{
num.print(false);
},"t2").start();
}
}
@Slf4j(topic = "c.TestNumber")
class TestNumber{
private int cnt = 1;
private boolean flag = true;
private final int count;
public TestNumber(int count){
this.count=count;
}
public void print(boolean flagN){
synchronized (this){
for (int i=0;i<count;i++){
while (flag!=flagN){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("{}",cnt);
cnt++;
flag=!flag;
this.notify();
}
}
}
}
result
23:45:24.559 c.TestNumber [t1] - 1
23:45:24.562 c.TestNumber [t2] - 2
23:45:24.562 c.TestNumber [t1] - 3
23:45:24.562 c.TestNumber [t2] - 4
23:45:24.562 c.TestNumber [t1] - 5
23:45:24.562 c.TestNumber [t2] - 6
23:45:24.562 c.TestNumber [t1] - 7
23:45:24.562 c.TestNumber [t2] - 8
23:45:24.562 c.TestNumber [t1] - 9
23:45:24.562 c.TestNumber [t2] - 10
park/unpark Realization
@Slf4j(topic = "c.TestSunPark")
public class TestSunPark {
static Thread t1;
static Thread t2;
public static void main(String[] args) {
// Alternate printing 5 Time
TestParkNum num = new TestParkNum(5);
t1 = new Thread(()->{
num.print(t2);
},"t1");
t2 = new Thread(()->{
num.print(t1);
},"t2");
t1.start();
t2.start();
LockSupport.unpark(t1);
}
}
@Slf4j(topic = "c.TestParkNum")
class TestParkNum{
private int cnt = 1;
private final int count;
public TestParkNum(int count){
this.count=count;
}
public void print(Thread next){
for (int i=0;i<count;i++){
LockSupport.park();
log.debug("{}",cnt);
cnt++;
LockSupport.unpark(next);
}
}
}
result
23:49:38.354 c.TestSunReenNum [t1] - 1
23:49:38.357 c.TestSunReenNum [t2] - 2
23:49:38.357 c.TestSunReenNum [t1] - 3
23:49:38.357 c.TestSunReenNum [t2] - 4
23:49:38.358 c.TestSunReenNum [t1] - 5
23:49:38.358 c.TestSunReenNum [t2] - 6
23:49:38.358 c.TestSunReenNum [t1] - 7
23:49:38.358 c.TestSunReenNum [t2] - 8
23:49:38.358 c.TestSunReenNum [t1] - 9
23:49:38.358 c.TestSunReenNum [t2] - 10
await/signal Realization
public class TestSunReen {
public static void main(String[] args) {
// Alternate printing 5 Time
TestSunReenNum num = new TestSunReenNum(5);
Condition condition = num.newCondition();
new Thread(()->{
num.print(true,condition);
},"t1").start();
new Thread(()->{
num.print(false,condition);
},"t2").start();
}
}
@Slf4j(topic = "c.TestSunReenNum")
class TestSunReenNum extends ReentrantLock {
private int cnt = 1;
private final int count;
private boolean flag = true;
TestSunReenNum(int count) {
this.count = count;
}
public void print(boolean flagN, Condition condition){
lock();
try {
for (int i=0;i<count;i++){
while (flag!=flagN){
condition.await();
}
log.debug("{}",cnt);
cnt++;
flag=!flag;
condition.signalAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
unlock();
}
}
}
result
23:51:38.603 c.TestSunReenNum [t1] - 1
23:51:38.606 c.TestSunReenNum [t2] - 2
23:51:38.606 c.TestSunReenNum [t1] - 3
23:51:38.607 c.TestSunReenNum [t2] - 4
23:51:38.607 c.TestSunReenNum [t1] - 5
23:51:38.607 c.TestSunReenNum [t2] - 6
23:51:38.607 c.TestSunReenNum [t1] - 7
23:51:38.607 c.TestSunReenNum [t2] - 8
23:51:38.607 c.TestSunReenNum [t1] - 9
23:51:38.607 c.TestSunReenNum [t2] - 10
03. Question two
Three threads print alternately abc 5 Time
wait/notify Realization
public class TestSun2 {
public static void main(String[] args) {
TestSun2Num num = new TestSun2Num(5);
new Thread(()->{
num.print("a",1);
}).start();
new Thread(()->{
num.print("b",2);
}).start();
new Thread(()->{
num.print("c",0);
}).start();
}
}
class TestSun2Num{
private int cnt = 1;
private final int count;
public TestSun2Num(int count){
this.count=count;
}
public void print(String str,int flag){
synchronized (this){
for (int i=0;i<count;i++){
while (cnt%3!=flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(str);
if (flag==0)
System.out.println();
cnt++;
this.notifyAll();
}
}
}
}
result
abc
abc
abc
abc
abc
park/unpark Realization
public class TestSun2Park {
static Thread t1;
static Thread t2;
static Thread t3;
public static void main(String[] args) {
TestSun2ParkNum num = new TestSun2ParkNum(5);
t1 = new Thread(()->{
num.print(1,"a",t2);
});
t2 = new Thread(()->{
num.print(2,"b",t3);
});
t3 = new Thread(()->{
num.print(0,"c",t1);
});
t1.start();
t2.start();
t3.start();
LockSupport.unpark(t1);
}
}
class TestSun2ParkNum{
private final int count;
TestSun2ParkNum(int count) {
this.count = count;
}
public void print(int flagN,String str,Thread next){
for (int i=0;i<count;i++){
LockSupport.park();
System.out.print(str);
if (str.equals("c"))
System.out.println();
LockSupport.unpark(next);
}
}
}
result
abc
abc
abc
abc
abc
await/signal Realization
public class TestSun2Reen {
public static void main(String[] args) {
TestReenNum num = new TestReenNum(5);
Condition condition1 = num.newCondition();
Condition condition2 = num.newCondition();
Condition condition3 = num.newCondition();
new Thread(()->{
num.print("a",condition1,condition2);
}).start();
new Thread(()->{
num.print("b",condition2,condition3);
}).start();
new Thread(()->{
num.print("c",condition3,condition1);
}).start();
Sleeper.sleep(1);
num.lock();
try {
condition1.signal();
}finally {
num.unlock();
}
}
}
class TestReenNum extends ReentrantLock {
private final int count;
TestReenNum(int count) {
this.count = count;
}
public void print(String str, Condition condition,Condition nextCondition){
lock();
try {
for (int i=0;i<count;i++){
condition.await();
System.out.print(str);
if (str.equals("c"))
System.out.println();
nextCondition.signalAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
unlock();
}
}
}
result
abc
abc
abc
abc
abc
04. What needs attention
1. We need to skillfully use the above methods .
2. Question one and question two are used await/signal Realization It's handled in a very different way , You can read it carefully Analyze these two methods
边栏推荐
- Detailed explanation of JVM memory model and structure (five model diagrams)
- Beisen Holdings' IPO: a total loss of 4.115 billion yuan in three years, and a total of 2.84 billion yuan in the previous nine rounds of financing
- 大厂面试官:千万级数据量的表,如何进行快速查询?
- sqlx库使用
- cv图像翻转,EmguCV图像旋转「建议收藏」
- 【面试:并发篇23:多线程:join】join再理解
- The adequacy of source evaluation forum · observation model test
- LeetCode刷题——猜数字大小II#375#Medium
- As a test, how to understand thread synchronization and asynchrony
- An interview question about concurrent reading and writing of map in golang
猜你喜欢

【面试:并发篇23:多线程:join】join再理解

字节一面:TCP 和 UDP 可以使用同一个端口吗?

Sentinel vs Hystrix 限流对比,到底怎么选?

零基础学习CANoe Panel(17)—— Panel CAPL Function

腾讯云数据库的可信可控之路

测试用例和缺陷报告模板

DDD的Go实战

Programmer's Guide to health quenching 5: introduction to sports Basics
![[manageengine]itsm application in retail industry](/img/25/e8d9a320c5d4b1cf2e187b61180991.png)
[manageengine]itsm application in retail industry

As a test, how to understand thread synchronization and asynchrony
随机推荐
Decompile app
Cesium 多边形渐变色纹理(Canvas)
Autojs learning - realize 3D perspective
An interview question about concurrent reading and writing of map in golang
Face and key point detection: yolo5face practice
[FAQ] access the HMS core push service, and the server sends messages. Cause analysis and solutions of common error codes
mysql导入数据时已改成csv utf8文件且文件名为英文,为什么还是导入失败
Six principles of C program design
Rent two or three things
Vivo official website app full model UI adaptation scheme
Basic method of black box (function) test
Dear bosses, how can I print the result of Flink SQL to the console and display it completely?
resize函数的作用「建议收藏」
Array of arm disassembly
An interview question about interface and implementation in golang
Reading the pointpillar code of openpcdet -- Part 3: Calculation of loss function
How to solve the problem of high concurrency and large traffic with PHP
【面试:并发篇23:多线程:join】join再理解
3阶有向完全图的所有非同构的子图(不同钩子图个数)
ES6 --- four powerful operators (?,? =,?.,?:)