码迷,mamicode.com
首页 > 编程语言 > 详细

三线程连续打印ABC

时间:2016-12-11 12:36:49      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:port   test   err   import   style   and   ati   ide   nts   

 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

标签:port   test   err   import   style   and   ati   ide   nts   

原文地址:http://www.cnblogs.com/noaman/p/6159253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!