マルチスレッド順印刷ABC
1328 ワード
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){
}
}
}
}
スレッドをインスタンス化するときに、スレッドの名前を指定します.
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();
}
}