有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印ABC十次,即:ABCABCABCABCABCABCABCABCABCABCABCABC……”
package com.time1227.Main;
/**
* 2011-12-28
* @author gujinzhi
*(转)
*/
public class Mian2 extends Thread{
//打印数量
private final static int maxCount = 10;
//线程锁1的数组
private static boolean[] bool = {true,false,false};
//线程锁的顺序
private int tag;
//run方法里循环的次数
private int count;
public Mian2(String ThredName,int tag){
super(ThredName);
this.tag = tag;
}
public static void main(String[] args) throws InterruptedException {
Thread ThreadA = new Mian2("A",0);
Thread ThreadB = new Mian2("B",1);
Thread ThreadC = new Mian2("C",2);
//获取开始线程当前时间的毫秒数
long timeStart = System.currentTimeMillis();
ThreadA.start();
ThreadB.start();
ThreadC.start();
//等待该线程终止
ThreadA.join();
ThreadB.join();
ThreadC.join();
//获取线程结束时当前时间的毫秒数
long timeEng = System.currentTimeMillis();
System.out.println();
System.out.println("耗时"+(timeEng-timeStart)+"ms");
}
public void run(){
try{
synchronized (bool) {
while(true){
if(bool[this.tag]){
//Thread.currentThread().getName()获取线程名字
System.out.print(Thread.currentThread().getName());
this.count ++;
bool[this.tag] = false;
bool[(this.tag+1)%3] = true;
bool[(this.tag+2)%3] = false;
//等待
bool.notifyAll();
if(count == maxCount ){
return;
}
}else{
//停止当前线程,再次while循环
bool.wait();
}
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
}