public class ThreadOfWait extends Thread { private int count = 0; @Override public void run() { String name = Thread.currentThread().getName(); while (count <30){ synchronized (this){ if(count %3==0){ printAndIncrease("A"); } if(count %3==1){ printAndIncrease("B"); } if(count %3==2){ printAndIncrease("C"); } } } } public void printAndIncrease(String a){ String name = Thread.currentThread().getName(); if(a.equals(name)){ System.out.println(name); count ++; this.notifyAll(); }else{ try { this.wait(); }catch (Exception e){ } } } }
在實例化該線程的時候指定線程的名稱:ide
public class TestThread { public static void main(String[] arags){ ThreadOfWait wait = ThreadOfWait(); Thread a1 = Thread(wait,"A"); Thread a2 = Thread(wait,"B"); Thread a3 = Thread(wait,"C"); a1.start(); a2.start(); a3.start(); } }