1 package test5; 2 3 import java.util.concurrent.locks.Condition; 4 import java.util.concurrent.locks.ReentrantLock; 5 6 class PrintThread implements Runnable{ 7 8 private ReentrantLock lock=new ReentrantLock(); 9 Condition condition = lock.newCondition(); 10 private int state=0; 11 12 @Override 13 public void run() { 14 String threadName=Thread.currentThread().getName(); 15 lock.lock(); 16 try { 17 for(int i=0;i<9;i++){ 18 if(threadName.equals("A")){ 19 while(state%3!=0){ 20 condition.await(); 21 } 22 }else if(threadName.equals("B")){ 23 while(state%3!=1){ 24 condition.await(); 25 } 26 }else if(threadName.equals("C")){ 27 while(state%3!=2){ 28 condition.await(); 29 } 30 } 31 state++; 32 System.out.println(threadName); 33 condition.signalAll(); 34 } 35 } catch (Exception e) { 36 // TODO: handle exception 37 }finally{ 38 lock.unlock(); 39 } 40 41 42 } 43 44 } 45 46 public class PrintABC{ 47 public static void main(String[] args) { 48 PrintThread pt=new PrintThread(); 49 Thread t1=new Thread(pt,"A"); 50 Thread t2=new Thread(pt,"B"); 51 Thread t3=new Thread(pt,"C"); 52 t1.start(); 53 t2.start(); 54 t3.start(); 55 } 56 }
时间: 2024-10-13 08:14:50