当前位置:网站首页>利用多线程按顺序连续输出abc10次
利用多线程按顺序连续输出abc10次
2022-04-23 09:57:00 【N. LAWLIET】
多线程无论是在面试还是在公司都是经常会出现和用到的技术。今天我通过一道小题融合多项多线程技术。
这道题是利用多线程连续输出ABC十次。首先,我先说明解决这道题的方法不唯一,而我只提供一种,其他方法希望读者自己尝试。第一步需要定义三个线程,继承Runnablej接口,重写其中方法并且加上synchronized锁,(synchronized是一种互斥同步锁,作用是在多线程程序中一次只能运行一个线程,并且同步更改),只用synchronized还不够吗,我们需要volatile关键字修饰一个变量用来控制线程执行顺序(volatile可以保证线程间的可见性和有序性,但是不能保证原子性,所以需要在合适的场景下才能保证线程安全)。通过java中的wait()方法(使用wait()方法后需要启动notify()方法才能重启线程)控制线程间隔。
public class ThreadABC {
private volatile static int flag = 1;
public static void main(String[] args) throws IOException, InterruptedException{
Thread threada = new Thread(new Runnable() {
@Override
public synchronized void run() {
try {
while(flag!=1) {
wait();
}
System.out.println("A");
flag = 2;
notify();
}catch (Exception e) {
e.printStackTrace();
}
}
});
Thread threadb = new Thread(new Runnable() {
@Override
public synchronized void run() {
try {
while(flag!=2) {
wait();
}
System.out.println("B");
flag =3;
notify();
}catch (Exception e) {
e.printStackTrace();
}
}
});
Thread threadc = new Thread(new Runnable() {
@Override
public synchronized void run() {
try {
while(flag !=3) {
wait();
}
System.out.println("C");
flag = 1;
notify();
}catch (Exception e) {
e.printStackTrace();
}
}
});
ExecutorService pool = Executors.newCachedThreadPool();
for(int i = 0;i<10;i++) {
pool.execute(threada);
pool.execute(threadb);
pool.execute(threadc);
}
}
}
版权声明
本文为[N. LAWLIET]所创,转载请带上原文链接,感谢
https://blog.csdn.net/jiangzuofengqiao/article/details/124307876
边栏推荐
- P1446 [hnoi2008] cards (Burnside theorem + DP count)
- GCD of p2257 YY (Mobius inversion)
- 0704、ansible----01
- Introduction to sap pi / PO login and basic functions
- Golang force buckle leetcode 396 Rotation function
- 使用IDEA开发Spark程序
- How to use SQL statement union to get another column of another table when the content of a column in a table is empty
- 论文阅读《Integrity Monitoring Techniques for Vision Navigation Systems》——5结果
- Computer network security experiment II DNS protocol vulnerability utilization experiment
- 第一章 Oracle Database In-Memory 相关概念(IM-1.1)
猜你喜欢
随机推荐
杰理之有时候发现内存被篡改,但是没有造成异常,应该如何查找?【篇】
[hdu6833] a very easy math problem
使用IDEA开发Spark程序
"Gu Yu series" airdrop
Easy to understand subset DP
DBA常用SQL语句(3)- cache、undo、索引和等待事件
杰理之系统事件有哪些【篇】
DBA常用SQL语句(4)- Top SQL
DBA常用SQL语句(2)— SGA和PGA
Longest common front string
Go语言实践模式 - 函数选项模式(Functional Options Pattern)
[CF 1425d] danger of mad snakes
Mobius inversion
Function realization of printing page
LeetCode 1249. Minimum Remove to Make Valid Parentheses - FB高频题1
Computer network security experiment II DNS protocol vulnerability utilization experiment
SAP 03-amdp CDs table function using 'with' clause
MapReduce压缩
SAP RFC_ CVI_ EI_ INBOUND_ Main BP master data creation example (Demo customer only)
0704、ansible----01







