题目:有A,B,C三个线程, A线程输出A, B线程输出B, C线程输出C,要求, 同时启动三个线程, 按顺序输出ABC, 循环10次。
解题思路:要按顺序输出ABC, 循环10次,就要控制三个线程同步工作,也就是说要让三个线程轮流输出,直到10个ABC全部输出则结束线程。这里用一个Lock对象来控制三个线程的同步。用一个int型变量COUNT标识由那个线程输出。
import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;public class PrintABC {public static int cnt = 0;public static final int COUNT = 30;public static void main(String[] args) {final Lock lock = new ReentrantLock();Thread A = new Thread(new Runnable(){@Overridepublic void run() {while(true){lock.lock();if(cnt>=COUNT){lock.unlock();return;}if(cnt%3==0){System.out.println("A");cnt++;}lock.unlock();} }});Thread B = new Thread(new Runnable(){public void run(){while(true){lock.lock();if(cnt>=COUNT){lock.unlock();return;}if(cnt%3==1){System.out.println("B");cnt++;}lock.unlock();}}});Thread C = new Thread(new Runnable(){public void run(){while(true){lock.lock();if(cnt>=COUNT){lock.unlock();return;}if(cnt%3==2){System.out.println("C");cnt++;}lock.unlock();}}});A.start();B.start();C.start();}}
程序运行结果如下:
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