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 }
一条线程连续打印ABC:
class PrintABC implements Runnable{ private Lock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); @Override public void run() { String threadName = Thread.currentThread().getName(); lock.lock(); int state = 0; try{ while(state < 10){ if(state % 3 == 0){ System.out.print("A "); }else if(state % 3 == 1){ System.out.print("B "); }else if(state % 3 == 2){ System.out.print("C "); } state++; } }finally { lock.unlock(); } } } public class ThreadDemo { public static void main(String[] args) { PrintABC p = new PrintABC(); Thread t = new Thread(p); t.start(); } }