书上给的例子都是ABCABC这种,比较简单,复杂点的如A0B0C0, A0A1A2没有,手动实现下,做个记录

1. A0 A1 A2 A3

 public class Demo0 {

     private static volatile  int nextPrintWho = 0;

     public static void main(String[] args) throws InterruptedException, NoSuchFieldException {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition(); Runnable runnable = ()-> {
lock.lock();
String name = Thread.currentThread().getName();
final int index = Integer.parseInt(name.substring(name.length() - 1, name.length()));
while (Demo0.nextPrintWho != index) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo0.nextPrintWho += 1;
println(Thread.currentThread().getName());
try {
condition.signAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
};
int size = 5;
List<Thread> threadList = new ArrayList<>(size);
for(int i=0; i<size; i++) {
threadList.add(new Thread(runnable,"A" + i));
}
threadList.forEach(i->i.start());
} private static void println(Object object) {
System.out.println(object);
} }

2.单condition实现ABC ABC ABC

 /**
* @author tele
* @Description 使用condition实现顺序启动线程 ABC ABC ABC
* @create 2019-12-24
*/
public class Demo1 { private static volatile int nextPrintWho = 1; public static void main(String[] args) throws InterruptedException, NoSuchFieldException {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition(); Runnable runnableA = ()-> {
lock.lock();
while (Demo1.nextPrintWho != 1) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo1.nextPrintWho = 2;
println(Thread.currentThread().getName());
try {
condition.signAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableB = ()-> {
lock.lock();
while (Demo1.nextPrintWho != 2) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo1.nextPrintWho = 3;
println(Thread.currentThread().getName());
try {
condition.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableC = ()-> {
lock.lock();
while (Demo1.nextPrintWho != 3) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo1.nextPrintWho = 1;
println(Thread.currentThread().getName());
try {
condition.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; for(int i=0; i<5; i++) {
new Thread(runnableA,"A").start();
new Thread(runnableB,"B").start();
new Thread(runnableC,"C").start();
} } private static void println(Object object) {
System.out.println(object);
} }

3.多个condition实现ABC ABC

 /**
* @author tele
* @Description 使用多个condition实现顺序启动线程 ABC ABC ABC
* @create 2019-12-24
*/
public class Demo2 { private static volatile int nextPrintWho = 1; public static void main(String[] args) throws InterruptedException, NoSuchFieldException {
ReentrantLock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition(); Runnable runnableA = ()-> {
lock.lock();
while (Demo2.nextPrintWho != 1) {
try {
conditionA.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo2.nextPrintWho = 2;
println(Thread.currentThread().getName());
try {
conditionB.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableB = ()-> {
lock.lock();
while (Demo2.nextPrintWho != 2) {
try {
conditionB.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo2.nextPrintWho = 3;
println(Thread.currentThread().getName());
try {
conditionC.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableC = ()-> {
lock.lock();
while (Demo2.nextPrintWho != 3) {
try {
conditionC.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo2.nextPrintWho = 1;
println(Thread.currentThread().getName());
try {
conditionA.signal();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; for(int i=0; i<5; i++) {
new Thread(runnableA,"A").start();
new Thread(runnableB,"B").start();
new Thread(runnableC,"C").start();
} } private static void println(Object object) {
System.out.println(object);
} }

4.A0 B0 C0 A1 B1 C1 A2 B2 C2

 /**
* @author tele
* @Description 使用condition实现顺序启动线程 A0 B0 C0 A1 B1 C1 A2 B2 C2
* @create 2019-12-24
*/
public class Demo3 { private static volatile int nextPrintWho = 0; private static volatile int order = 1; private static final int ORDER_A = 1; private static final int ORDER_B = 2; private static final int ORDER_C = 3; public static void main(String[] args) throws InterruptedException, NoSuchFieldException {
ReentrantLock lock = new ReentrantLock();
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition(); Runnable runnableA = ()-> {
lock.lock();
String name = Thread.currentThread().getName(); final int index = Integer.parseInt(name.substring(name.length() - 1, name.length())); while (!name.contains("A") || Demo3.nextPrintWho != index || Demo3.order != Demo3.ORDER_A) {
try {
conditionA.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
} Demo3.order = Demo3.ORDER_B;
println(Thread.currentThread().getName());
try {
conditionB.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableB = ()-> {
lock.lock();
String name = Thread.currentThread().getName(); final int index = Integer.parseInt(name.substring(name.length() - 1, name.length())); while (!name.contains("B") || Demo3.nextPrintWho != index || Demo3.order != Demo3.ORDER_B) {
try {
conditionB.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo3.order = Demo3.ORDER_C;
println(Thread.currentThread().getName());
try {
conditionC.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableC = ()-> {
lock.lock();
String name = Thread.currentThread().getName();
final int index = Integer.parseInt(name.substring(name.length() - 1, name.length()));
while (!name.contains("C") || Demo3.nextPrintWho != index || Demo3.order != Demo3.ORDER_C) {
try {
conditionC.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo3.nextPrintWho += 1;
Demo3.order = Demo3.ORDER_A;
println(Thread.currentThread().getName());
try {
conditionA.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; for(int i=0; i<5; i++) {
new Thread(runnableA,"A" + i).start();
new Thread(runnableB,"B" + i).start();
new Thread(runnableC,"C" + i).start();
} } private static void println(Object object) {
System.out.println(object);
} }

5.A0 A1 A2 A3 B0 B1 B2 B3

 /**
* @author tele
* @Description 使用condition实现顺序启动线程 A0 A1 A2 A3 B0 B1 B2 B3
* @create 2019-12-24
*/
public class Demo4 { private static volatile int nextPrintWho = 0; private static volatile int order = 1; private static final int LIST_SIZE = 5; private static final int ORDER_A = 1; private static final int ORDER_B = 2; private static final int ORDER_C = 3; public static void main(String[] args) throws InterruptedException, NoSuchFieldException {
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
Runnable runnableA = ()-> {
lock.lock();
String name = Thread.currentThread().getName(); final int index = Integer.parseInt(name.substring(name.length() - 1, name.length())); while (!name.contains("A") || Demo4.nextPrintWho != index || Demo4.order != Demo4.ORDER_A) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo4.nextPrintWho += 1;
if(Demo4.nextPrintWho == LIST_SIZE) {
Demo4.order = Demo4.ORDER_B;
Demo4.nextPrintWho = 0;
}
println(Thread.currentThread().getName());
try {
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableB = ()-> {
lock.lock();
String name = Thread.currentThread().getName(); final int index = Integer.parseInt(name.substring(name.length() - 1, name.length())); while (!name.contains("B") || Demo4.nextPrintWho != index || Demo4.order != Demo4.ORDER_B) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo4.nextPrintWho += 1;
if(Demo4.nextPrintWho == LIST_SIZE) {
Demo4.order = Demo4.ORDER_C;
Demo4.nextPrintWho = 0;
}
println(Thread.currentThread().getName());
try {
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; Runnable runnableC = ()-> {
lock.lock();
String name = Thread.currentThread().getName();
final int index = Integer.parseInt(name.substring(name.length() - 1, name.length()));
while (!name.contains("C") || Demo4.nextPrintWho != index || Demo4.order != Demo4.ORDER_C) {
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Demo4.order = Demo4.ORDER_C;
Demo4.nextPrintWho += 1;
println(Thread.currentThread().getName());
try {
condition.signalAll();
}catch (Exception e) {
e.printStackTrace();
}finally {
if(lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}; List<Thread> threadAList = new ArrayList<>(LIST_SIZE);
List<Thread> threadBList = new ArrayList<>(LIST_SIZE);
List<Thread> threadCList = new ArrayList<>(LIST_SIZE); for(int i=0; i<LIST_SIZE; i++) {
threadAList.add(new Thread(runnableA,"A" + i));
threadBList.add(new Thread(runnableB,"B" + i));
threadCList.add(new Thread(runnableC,"C" + i));
} threadAList.forEach(i->i.start());
threadBList.forEach(i->i.start());
threadCList.forEach(i->i.start()); } private static void println(Object object) {
System.out.println(object);
} }

使用condition 实现线程顺序执行的更多相关文章

  1. Java中如何保证线程顺序执行

    只要了解过多线程,我们就知道线程开始的顺序跟执行的顺序是不一样的.如果只是创建三个线程然后执行,最后的执行顺序是不可预期的.这是因为在创建完线程之后,线程执行的开始时间取决于CPU何时分配时间片,线程 ...

  2. Android中让多个线程顺序执行探究

    线程调度是指按照特定机制为多个线程分配CPU的使用权. 有两种调度模型:分时调度模型和抢占式调度模型. 分时调度模型:是指让所有的线程轮流获得cpu的使用权,并且平均分配每个线程占用的CPU的时间片. ...

  3. T1,T2,T3 三个线程顺序执行

    T1,T2,T3 三个线程顺序执行 现在有 T1.T2.T3 三个线程,你怎样保证 T2 在 T1 执行完后执行,T3 在 T2 执行完后执行?(T1->T2->T3) 这个线程问题通常会 ...

  4. c#线程顺序执行

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threa ...

  5. Java中线程顺序执行

    现有线程threadone.threadtwo和threadthree,想要的运行顺序为threadone->threadtwo->threadthree,应该如何处理?这里需要用到一个简 ...

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

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

  7. 三个线程abc顺序执行

    1.使用synchronized悲观锁(秋招阿里的一个笔试题,应该写的比较复杂,然后就没有然后了o(╥﹏╥)o) public class ThreadThreadp { private int fl ...

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

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

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

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

随机推荐

  1. linux CentOs 7.4 64位 系统下 nuxt部署 、nginx 安装、node环境及软连接,pm2软连接

    一.nginx安装 1.安装依赖包 //一键安装上面四个依赖 yum -y install gcc zlib zlib-devel pcre-devel openssl openssl-devel 2 ...

  2. 【JZOJ4860】【NOIP2016提高A组集训第7场11.4】分解数

    题目描述 Dpstr学习了动态规划的技巧以后,对数的分解问题十分感兴趣. Dpstr用此过程将一个正整数x分解成若干个数的乘积:一开始令集合A中只有一个元素x,每次分解时从A中取一个元素a并找出两个大 ...

  3. python 文件读写编码

  4. form表单提交,后台怎么获取select的值?后台直接获取即可,和input方式一样。

    form表单提交,后台怎么获取select的值? 后台直接获取即可,和后台获取input的值方式一样. form提交后,后台直接根据select的name获取即可,即getPara("XXX ...

  5. 2019-10-23-WPF-使用-SharpDx-渲染博客导航

    title author date CreateTime categories WPF 使用 SharpDx 渲染博客导航 lindexi 2019-10-23 21:10:13 +0800 2019 ...

  6. Python基础:05集合类型

    Python中,集合对象是一组无序排列的可哈希的值.所以集合成员可以做字典中的键.集合中的元素都是唯一的. 集合(sets)有两种不同的类型,可变集合(set) 和 不可变集合(frozenset). ...

  7. es6 默认参数、rest参数、扩展运算符

    1.默认值 现在可以在定义函数的时候指定参数的默认值了,而不用像以前那样通过逻辑或操作符来达到目的了. function sayHello(name){ //传统的指定默认参数的方式 var name ...

  8. iOS学习--详解UIView的 contentStretch属性

    通过实例和图片理解UIView的contentStretch属性 方法 通过一个图片建立一个简单的UIImageView 设置它的contentStretch属性 修改它的frame属性 观察 测试用 ...

  9. ListView 适配器实现getviewtypecount() 数组越界IndexOutOfBoundException

    ListView中Item的多布局显示,需要用到了getviewtypecount和getItemViewType这两个重写方法,但是做完后出现了如下提示错误: java.lang.ArrayInde ...

  10. BERT可视化工具bertviz体验

    BERT可视化工具体验:bertviz是用于BERT模型注意力层的可视化页面. 1,bertviz的github地址:https://github.com/jessevig/bertviz 2,将be ...