三个线程abc顺序执行
1.使用synchronized悲观锁
(秋招阿里的一个笔试题,应该写的比较复杂,然后就没有然后了o(╥﹏╥)o)
public class ThreadThreadp {
private int flag = 0;
public synchronized void printa() throws InterruptedException {
while (true)
{
if(flag ==0)
{
System.out.print("A");
flag = 1;
notifyAll();
}
wait();
}
}
public synchronized void printb() throws InterruptedException {
while (true)
{
if(flag ==1)
{
System.out.print("B");
flag = 2;
notifyAll();
}
wait();
}
}
public synchronized void printc() throws InterruptedException {
while (true) {
if (flag == 2) {
System.out.print("C");
Thread.sleep(1000);
flag = 0;
notifyAll();
}
wait();
}
}
public static void main(String[]args) throws InterruptedException
{
ThreadThreadp t = new ThreadThreadp();
PrintA printA = new PrintA(t);
PrintB printB = new PrintB(t);
PrintC printC = new PrintC(t);
Thread t1 = new Thread(printA);
Thread t2 = new Thread(printB);
Thread t3 = new Thread(printC);
t1.start();
t2.start();
t3.start();
//Thread t11 = new Thread(printA);
//Thread t21 = new Thread(printB);
//Thread t31 = new Thread(printC);
//t11.start();
//t21.start();
//t31.start();
}
}
class PrintA implements Runnable{
private ThreadThreadp t;
PrintA(ThreadThreadp t){
this.t=t;
}
@Override
public void run() {
try {
t.printa();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintB implements Runnable{
private ThreadThreadp t;
PrintB(ThreadThreadp t){
this.t=t;
}
@Override
public void run() {
try {
t.printb();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class PrintC implements Runnable{
private ThreadThreadp t;
PrintC(ThreadThreadp t){
this.t=t;
}
@Override
public void run() {
try {
t.printc();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2.使用Lock+Condition
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class threadsan {
public static void main(String [] args)
{
PrintABC printABC = new PrintABC();
new Thread(new Runnable() {
@Override
public void run() {
printABC.printA();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
printABC.printB();
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
printABC.printC();
}
}).start();
}
} class PrintABC{
private final Lock lock = new ReentrantLock();
private Condition lockA = lock.newCondition();
private Condition lockB = lock.newCondition();
private Condition lockC = lock.newCondition();
int flag = 0; public void printA()
{
lock.lock();
try {
while (true)
{
while (flag!=0)
lockA.await();
System.out.print("A");
flag =1;
lockB.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB()
{
lock.lock();
try {
while (true)
{
while (flag!=1)
lockB.await();
System.out.print("B");
flag =2;
lockC.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printC()
{
lock.lock();
try {
while (true)
{
while (flag!=2)
lockC.await();
System.out.print("C");
Thread.sleep(1000);
flag =0;
lockA.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
3.使用Semaphore实现
//semaphore没用过。。。参考
import java.util.concurrent.Semaphore; /**
* Created by huali on 2018/7/25.
*/
public class PrintABCRotationUsingSemaphore {
public static void main(String[] args) {
PrintABCUsingSemaphore printABC = new PrintABCUsingSemaphore();
new Thread(() -> printABC.printA()).start();
new Thread(() -> printABC.printB()).start();
new Thread(() -> printABC.printC()).start();
}
} class PrintABCUsingSemaphore {
private Semaphore semaphoreA = new Semaphore(1);
private Semaphore semaphoreB = new Semaphore(0);
private Semaphore semaphoreC = new Semaphore(0);
//private int attempts = 0; public void printA() {
print("A", semaphoreA, semaphoreB);
} public void printB() {
print("B", semaphoreB, semaphoreC);
} public void printC() {
print("C", semaphoreC, semaphoreA);
} private void print(String name, Semaphore currentSemaphore, Semaphore nextSemaphore) {
for (int i = 0; i < 10; ) {
try {
currentSemaphore.acquire();
//System.out.println(Thread.currentThread().getName()+" try to print "+name+", attempts : "+(++attempts));
System.out.println(Thread.currentThread().getName() +" print "+ name);
i++;
nextSemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
另外参考链接 三个线程轮流执行顺序打印ABC(一):使用Semaphore实现
使用信号量Semaphore循环打印ABC
三个线程轮流执行顺序打印ABC(二):使用Lock+Condition实现
三个线程轮流执行顺序打印ABC(三):使用Lock实现
————————————————
版权声明:本文为CSDN博主「Angel_Zhl」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_33915826/article/details/81205938
三个线程abc顺序执行的更多相关文章
- 用三个线程按顺序循环打印ABC三个字母
有两种方法:semaphore信号量和mutex互斥锁.需要注意的是C++11已经没有semaphore. C++ 并发编程(六):信号量(Semaphore) - 止于至善 - SegmentFau ...
- Qt 控制线程的顺序执行(使用QWaitCondition,并且线程类的run函数里记得加exec(),使得线程常驻)
背景项目中用到多线程,对线程的执行顺序有要求: A.一个线程先收数据 B.一个线程处理数据 C.一个线程再将处理后的数据发送出去 要求三个线程按照ABC的顺序循环执行. 思路子类化多线程方法 重写子类 ...
- C#之使用AutoResetEvent实现线程的顺序执行
前几天一朋友问我如何实现线程的顺序执行,说真的,虽然看过CLR这本书,也把线程部分拜读了两遍,但是这个问题出来之后还是没有一个思路.今天在搜索资料的时候无意中再次看到AutoResetEvent这个东 ...
- C#中添加三个线程同时启动执行某一方法,并依次调用某方法中的循环打印输。
添加三个线程同时启动执行某一方法,并依次调用某方法中的打印输:ABC ABC ABC ABC 实现代码如下: using System; using System.Collections.Generi ...
- java 多线程 实现多个线程的顺序执行
场景 编写一个程序,启动三个线程,三个线程的name分别是A,B,C:,每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC... 使用 synchronized 实现 public cla ...
- 【Java并发】线程的顺序执行
/** * 问题:有线程a.b.c,如何让它们顺序执行? * 方式一:可用Join()方法实现 * 方式二:可用newSingleThreadExecutor() * Created by Smile ...
- 三个线程ABC,交替打印ABC
转载与:https://www.cnblogs.com/x_wukong/p/4009709.html 创建3个线程,让其交替打印ABC . 输出如下: ABCABCABCABC. 方法:使用syn ...
- [Thread] 多线程顺序执行
Join 主线程join 启动线程t1,随后调用join,main线程需要等t1线程执行完毕后继续执行. public class MainJoin { static class MyThread i ...
- 三个线程T1,T2,T3.保证顺序执行的三种方法
经常看见面试题:有三个线程T1,T2,T3,有什么方法可以确保它们按顺序执行.今天手写测试了一下,下面贴出目前想到的3种实现方式 说明:这里在线程中我都用到了sleep方法,目的是更容易发现问题.之前 ...
随机推荐
- vue 组件高级用法(递归组件,内联模板,动态组件,异步组件)
- 2019牛客多校B Beauty Values——思维题
题目 求所有子区间中不同元素之和. 分析 枚举相邻的相同数字形成的区间,计算它是哪些区间的子区间,每次有-1的贡献,将其从总贡献中减去. #include<bits/stdc++.h> u ...
- BZOJ4706 B君的多边形 (超级卡特兰数/施罗德数)
题目 权限题QAQ 题解 超级卡特兰数/施罗德数 CODE #include <bits/stdc++.h> using namespace std; const int MAXN = 1 ...
- waitgroup等待退出
等待一组协程结束,用sync.WaitGroup操作 package main import ( "fmt" "sync" "time" ) ...
- js中int和string数据类型互相转化实例
今天做项目的时候,碰到一个问题,需要把String类型的变量转化成int类型的.按照常规,我写了var i = Integer.parseInt("112");但控制台报错,说是“ ...
- DOM Diff(差分)算法
1. 算法由来 React调用render()方法后,会生成一个React元素组成的树. 再次调用,生成一个新的树.React比较两者的差异,然后更新UI. 如果单纯使用算法,来查找两个DOM树的差异 ...
- soap协议测试
soap就是http发送xml数据 1.soap协议提包含下列元素,红色标注为必须 2.soap消息基本结构 3.http+xml方式测试soap协议
- asp.net利用webuploader实现超大文件分片上传、断点续传
ASP.NET上传文件用FileUpLoad就可以,但是对文件夹的操作却不能用FileUpLoad来实现. 下面这个示例便是使用ASP.NET来实现上传文件夹并对文件夹进行压缩以及解压. ASP.NE ...
- 删除唯一性约束unique
删除唯一性约束 语法如下: alter table tableName drop index key_name;#删除唯一性约束,实际就是删除索引 drop index key_name on tab ...
- 在默认使用apache中央仓库时, 报错 protocol_version
https://cloud.tencent.com/developer/ask/136221/answer/241408 2018年6月,为了提高安全性和符合现代标准,不安全的TLS 1.0和1.1协 ...