您的位置:首页 > 其它

多线程顺序打印ABC

2016-04-26 00:00 399 查看
摘要: 多线程的基本应用

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: