要用condition實現(xiàn)類似這樣的效果
thread a 1thread a 2thread a 3
thread b 1thread b 2thread b 3
thread c 1thread c 2thread c 3
thread a 1thread a 2thread a 3
thread b 1thread b 2thread b 3
thread c 1thread c 2thread c 3
。。。
為什么我寫的代碼只能打印一輪?
代碼:
1 /**
2 * 利用condition實現(xiàn)順序執(zhí)行
3 * @author ko
4 *
5 */
6 public class MyService {
7 protected ReentrantLock lock = new ReentrantLock();
8 protected Condition conditionA = lock.newCondition();
9 protected Condition conditionB = lock.newCondition();
10 protected Condition conditionC = lock.newCondition();
11
12 public void printA() throws InterruptedException{
13 lock.lock();
14 for (int j = 0; j < 10; j++) {
15 for (int i = 1; i < 4; i++) {
16 System.out.println(Thread.currentThread().getName()+" "+i);
17 }
18 System.out.println("");
19 conditionA.await();
20 conditionB.signal();
21 }
22 lock.unlock();
23 }
24 public void printB() throws InterruptedException{
25 lock.lock();
26 for (int j = 0; j < 10; j++) {
27 for (int i = 1; i < 4; i++) {
28 System.out.println(Thread.currentThread().getName()+" "+i);
29 }
30 System.out.println("");
31 conditionB.await();
32 conditionC.signal();
33 }
34 lock.unlock();
35 }
36 public void printC() throws InterruptedException{
37 lock.lock();
38 for (int j = 0; j < 10; j++) {
39 for (int i = 1; i < 4; i++) {
40 System.out.println(Thread.currentThread().getName()+" "+i);
41 }
42 System.out.println("");
43 conditionC.await();
44 conditionA.signal();
45 }
46 lock.unlock();
47 }
48 }
1 public class ThreadA extends Thread {
2 protected MyService myService;
3
4 public ThreadA(MyService myService) {
5 super();
6 this.myService = myService;
7 }
8
9 public void run() {
10 try {
11 myService.printA();
12 } catch (InterruptedException e) {
13 e.printStackTrace();
14 }
15 }
16 }
1 public class ThreadB extends Thread {
2 protected MyService myService;
3
4 public ThreadB(MyService myService) {
5 super();
6 this.myService = myService;
7 }
8
9 public void run() {
10 try {
11 myService.printB();
12 } catch (InterruptedException e) {
13 e.printStackTrace();
14 }
15 }
16 }
1 public class ThreadC extends Thread {
2 protected MyService myService;
3
4 public ThreadC(MyService myService) {
5 super();
6 this.myService = myService;
7 }
8
9 public void run() {
10 try {
11 myService.printC();
12 } catch (InterruptedException e) {
13 e.printStackTrace();
14 }
15 }
16 }
1 /**
2 * 測試類
3 * @author ko
4 *
5 */
6 public class Test {
7 public static void main(String[] args) {
8 MyService myService = new MyService();
9
10 ThreadA ta = new ThreadA(myService);
11 ta.setName("thread a");
12 ta.start();
13
14 ThreadB tb = new ThreadB(myService);
15 tb.setName("thread b");
16 tb.start();
17
18 ThreadC tc = new ThreadC(myService);
19 tc.setName("thread c");
20 tc.start();
21 }
22 }
結(jié)果,只能打印一輪。。。
?
?
添加回答
舉報
0/150
提交
取消