三线程连续打印ABC

Posted noaman_wgs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了三线程连续打印ABC相关的知识,希望对你有一定的参考价值。

 1 package test5;
 2 
 3 import java.util.concurrent.locks.Condition;
 4 import java.util.concurrent.locks.ReentrantLock;
 5 
 6 class PrintThread implements Runnable{
 7 
 8     private ReentrantLock lock=new ReentrantLock();
 9     Condition condition = lock.newCondition();
10     private int state=0;
11     
12     @Override
13     public void run() {
14         String threadName=Thread.currentThread().getName();
15         lock.lock();
16         try {
17             for(int i=0;i<9;i++){
18                 if(threadName.equals("A")){
19                     while(state%3!=0){
20                         condition.await();
21                     }
22                 }else if(threadName.equals("B")){
23                     while(state%3!=1){
24                         condition.await();
25                     }
26                 }else if(threadName.equals("C")){
27                     while(state%3!=2){
28                         condition.await();
29                     }
30                 }
31                 state++;
32                 System.out.println(threadName);
33                 condition.signalAll();
34             }
35         } catch (Exception e) {
36             // TODO: handle exception
37         }finally{
38             lock.unlock();
39         }
40         
41         
42     }
43 
44 }
45 
46 public class PrintABC{
47     public static void main(String[] args) {
48         PrintThread pt=new PrintThread();
49         Thread t1=new Thread(pt,"A");
50         Thread t2=new Thread(pt,"B");
51         Thread t3=new Thread(pt,"C");
52         t1.start();
53         t2.start();
54         t3.start();
55     }
56 }

 

以上是关于三线程连续打印ABC的主要内容,如果未能解决你的问题,请参考以下文章

[******] java多线程连续打印abc

多线程面试题之三线程按顺序交替打印ABC的方法

三个线程交替打印ABC100次问题思考

顺序打印ABC算法题

顺序打印ABC算法题

java多线程:结合多线程交替打印10次abc实例,对wait/notify使用的彻底理解