/**
* 这里默认模拟三个线程顺序打印,所以用正在打印的当前数字printCount%3得到当前期望唤醒的线程
* 另外用ReentrantLock效率应该会更高
*/
public class MyThread extends Thread {
private Object lock;
//指定线程号
private int threadCount;
volatile private static int printCount =1;
public MyThread(Object lock, int t_count) {
super();
this.lock = lock;
this.threadCount = t_count;
}
@Override
public void run() {
try {
synchronized (lock) {
while (true) {
if (printCount %3 ==threadCount) {
System.out.println("thread name=" +Thread.currentThread().getName() +"; run count=" +printCount);
lock.notifyAll();
printCount++;
if (printCount ==99) {
break;
}
}else {
lock.wait();
}
}
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
网友评论