3个线程分别打印123


 1 import java.util.concurrent.locks.Condition;
 2 import java.util.concurrent.locks.ReentrantLock;
 3 
 4 public class ThreadTest {
 5 
 6     public static void main(String[] args) {
 7         new Thread(new PrintNumber(1)).start();
 8         new Thread(new PrintNumber(2)).start();
 9         new Thread(new PrintNumber(3)).start();
10     }
11 }
12 
13 class PrintNumber implements Runnable {
14 
15     private static final ReentrantLock LOCK = new ReentrantLock();
16 
17     private static final Condition[] pArray = new Condition[3];
18 
19     private final Integer printNumber;
20 
21     private volatile static Integer incNumber = 1;
22 
23     static {
24         //打印1的条件
25         pArray[0] = LOCK.newCondition();
26         //打印2的条件
27         pArray[1] = LOCK.newCondition();
28         //打印3的条件
29         pArray[2] = LOCK.newCondition();
30     }
31 
32     PrintNumber(Integer pn) {
33         this.printNumber = pn;
34     }
35 
36     void print() {
37         LOCK.lock();
38         try {
39             //否决条件
40             while (!incNumber.equals(printNumber)) {
41                 //挂起不符合条件的线程
42                 Integer temp = printNumber - 1;
43                 pArray[temp].await();
44             }
45             //action
46             System.out.println(incNumber);
47             incNumber++;
48             if (incNumber > 3) {
49                 incNumber = 1;
50             }
51             //通知下个打印的线程 激活
52             Integer temp = incNumber - 1;
53             pArray[temp].signalAll();
54 
55         } catch (Exception ex) {
56             ex.printStackTrace();
57         } finally {
58             LOCK.unlock();
59         }
60     }
61 
62     @Override
63     public void run() {
64         while (true) {
65             print();
66         }
67     }
68 }

 

 

利用 ReentrantLock 的condition 合理的激活 对应的线程  杜绝 提前激活不需要的线程 

posted @ 2018-02-25 10:38  沐松  阅读(1557)  评论(0编辑  收藏  举报