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. python3 读取avro文件

    官网示例文档:http://avro.apache.org/docs/current/gettingstartedpython.html#download_install 需要注意的是,官网给出的是p ...

  2. Windows 对外开放端口号

    前记 今天在做 Kafka 消息传输时,本地连接服务器的 Kafka 出现问题.连接不上,想到新的服务器应该是防火墙关闭所致. 我呢,就用了最直接暴力的方法:关闭防火墙~~~~(哈哈哈) 问题是解决了 ...

  3. webpack 配置react脚手架(二):热更新

    下面继续配置 webpack dev server    hot module replacement: 首先配置dev-server     安装     npm i webpack-dev-ser ...

  4. kafka读书笔记《kafka并不难学》

    ======第一章 1 在高并发场景,如大量插入.更新数据库会导致锁表,导致连接数过多的异常,此时需要消息队列来缓冲一下.消息队列通过异步处理请求来缓解压力 2 消息队列采用异步通信机制消息队列拥有先 ...

  5. HttpReader

    头文件: #pragma once #include <afxinet.h> class CSF_HttpDataReader { public: CSF_HttpDataReader(v ...

  6. python - django (查询、聚合、分组)

    # """ ---- 正向查询按字段,反向查询按表名 一: 一对多 正向查询:(字段对象.关联表.查询字段) x_obj = models.Book.objects.fi ...

  7. HDU-1028-Ignatius and the Princess III(母函数)

    链接: https://vjudge.net/problem/HDU-1028 题意: "Well, it seems the first problem is too easy. I wi ...

  8. sql server if exists和 if not exists 的关键字用法

    if exists和if not exists关键字用法   1.介绍  if not exists 即如果不存在,if exists 即如果存在 2.使用  a.判断数据库不存在时  if not ...

  9. How to Fix a Frozen Mac When Updating macOS

    How to Fix a Frozen Mac When Updating macOS By Mike Tee – Posted on Sep 1, 2019 in Mac   While macOS ...

  10. 004_Python3 注释

    确保对模块, 函数, 方法和行内注释使用正确的风格 Python中的注释有单行注释和多行注释:Python中单行注释以 # 开头,例如::# 这是一个注释print("Hello, Worl ...