題目:有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(){ @Override public 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