题目:有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C,要求, 同时启动三个线程, 按顺序输出ABC, 循环10次。
解题思路:要按顺序输出ABC, 循环10次,就要控制三个线程同步工作,也就是说要让三个线程轮流输出,直到10个ABC全部输出则结束线程。这里用一个Lock对象来控制三个线程的同步。用一个int型变量state标识由那个线程输出。
1 package com.thread;
2
3 import java.util.concurrent.locks.Lock;
4 import java.util.concurrent.locks.ReentrantLock;
5
6 public class ABC {
7 private static int state = 0;
8
9 public static void main(String[] args) {
10 final Lock l = new ReentrantLock();
11
12 Thread A = new Thread(new Runnable(){
13 @Override
14 public void run() {
15 while (state<=30) {
16 l.lock();
17 if(state%3==0){
18 System.out.println(“A”);
19 state ++;
20 }
21 l.unlock();
22 }
23 }
24 });
25 Thread B = new Thread(new Runnable(){
26 @Override
27 public void run() {
28 while (state<=30) {
29 l.lock();
30 if(state%3==1){
31 System.out.println(“B”);
32 state ++;
33 }
34 l.unlock();
35 }
36 }
37 });
38 Thread C = new Thread(new Runnable(){
39 @Override
40 public void run() {
41 while (state<=30) {
42 l.lock();
43 if(state%3==2){
44 System.out.println(“C”);
45 state ++;
46 }
47 l.unlock();
48 }
49 }
50 });
51 A.start();
52 B.start();
53 C.start();
54 }
55
56 }
运行结果:
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C