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顺序执行的更多相关文章

  1. 用三个线程按顺序循环打印ABC三个字母

    有两种方法:semaphore信号量和mutex互斥锁.需要注意的是C++11已经没有semaphore. C++ 并发编程(六):信号量(Semaphore) - 止于至善 - SegmentFau ...

  2. Qt 控制线程的顺序执行(使用QWaitCondition,并且线程类的run函数里记得加exec(),使得线程常驻)

    背景项目中用到多线程,对线程的执行顺序有要求: A.一个线程先收数据 B.一个线程处理数据 C.一个线程再将处理后的数据发送出去 要求三个线程按照ABC的顺序循环执行. 思路子类化多线程方法 重写子类 ...

  3. C#之使用AutoResetEvent实现线程的顺序执行

    前几天一朋友问我如何实现线程的顺序执行,说真的,虽然看过CLR这本书,也把线程部分拜读了两遍,但是这个问题出来之后还是没有一个思路.今天在搜索资料的时候无意中再次看到AutoResetEvent这个东 ...

  4. C#中添加三个线程同时启动执行某一方法,并依次调用某方法中的循环打印输。

    添加三个线程同时启动执行某一方法,并依次调用某方法中的打印输:ABC ABC ABC ABC 实现代码如下: using System; using System.Collections.Generi ...

  5. java 多线程 实现多个线程的顺序执行

    场景 编写一个程序,启动三个线程,三个线程的name分别是A,B,C:,每个线程将自己的ID值在屏幕上打印5遍,打印顺序是ABCABC... 使用 synchronized 实现 public cla ...

  6. 【Java并发】线程的顺序执行

    /** * 问题:有线程a.b.c,如何让它们顺序执行? * 方式一:可用Join()方法实现 * 方式二:可用newSingleThreadExecutor() * Created by Smile ...

  7. 三个线程ABC,交替打印ABC

    转载与:https://www.cnblogs.com/x_wukong/p/4009709.html 创建3个线程,让其交替打印ABC . 输出如下:  ABCABCABCABC. 方法:使用syn ...

  8. [Thread] 多线程顺序执行

    Join 主线程join 启动线程t1,随后调用join,main线程需要等t1线程执行完毕后继续执行. public class MainJoin { static class MyThread i ...

  9. 三个线程T1,T2,T3.保证顺序执行的三种方法

    经常看见面试题:有三个线程T1,T2,T3,有什么方法可以确保它们按顺序执行.今天手写测试了一下,下面贴出目前想到的3种实现方式 说明:这里在线程中我都用到了sleep方法,目的是更容易发现问题.之前 ...

随机推荐

  1. k8s的高可用

    一.高可用原理   配置一台新的master节点,然后在每台node节点上安装nginx,nginx通过内部的负载均衡将node节点上需要通过访问master,kube-apiserver组件的请求, ...

  2. js+css 动效+1的效果

    点击数值 +1 的动效 vue data:{ timer: null,plus:''// 次数 } method:{ animate(plus) { var _this = this; clearIn ...

  3. pandas 3

    参考资料:https://mp.weixin.qq.com/s/9z3JVBkZpasC_F0ar_7JJA 删除多列:df.drop(col_names_list, axis=1, inplace= ...

  4. Django后台中文乱码

    无论如何,刚开始一定要写上默认编码utf8!!!!!! 第一种办法: 检查 ...\Lib\site-packages\Django-1.10.2-py2.7.egg\django\conf\loca ...

  5. 前端项目中的必要文件-【robots.txt】

    放在src文件下::   robots.txt     告诉搜索引擎,该网站的被允许扒取得网页和静止扒取得     facicon.ico      网站地址栏的显示图   humans.txt   ...

  6. Vue 定义全局变量

    main.js 中定义 import Ws from './lib/ws' import ElementUI from 'element-ui'; import GlobalFunc from './ ...

  7. TDOA 之 基站逻辑代码实现

    在前一篇博文里描述了基站的逻辑部分,这里贴出来具体代码实现.https://www.cnblogs.com/tuzhuke/p/11689881.html 1 Sync 信息部分 case 'S': ...

  8. 服务器nginx部署PHP项目样式不出来要注意的小问题

    服务器使用nginx部署PHP项目的时候如果样式没有 出来,那么很可能 location 块里出问题了. 比如 location / { root /home/wwwroot/default/php_ ...

  9. [笔记] 三元环 && 四元环计数

    Thanks to i207M && iki9! 三元环计数 无向图的三元环计数 我们首先需要对无向边按一定规则定向: 设 \(in[u]\) 表示 \(u\) 的度数 若 \(in[ ...

  10. kalilinux MSF数据库的连接

    需要自动连接数据库.如下设置.