題目:有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
