class Worker implements Runnable{
/** 全局的一个信息,用来确定是哪个线程在工作 */
private static int count = 0;
/** 线程的标志 */
private int id;
/** 线程已工作次数 */
private int pCount;
public Worker(int id){
this.id = id;
}
public void run() {
synchronized ("lock") {
for (;;) {
if(count%3==id){
System.out.print(Thread.currentThread().getName());
count++;
pCount++;
"lock".notifyAll();
if(pCount==10)
break;
}else{
try {
"lock".wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args)
{
new Thread(new Worker(0),"A").start();
new Thread(new Worker(1),"B").start();
new Thread(new Worker(2),"C").start();
}
/** 全局的一个信息,用来确定是哪个线程在工作 */
private static int count = 0;
/** 线程的标志 */
private int id;
/** 线程已工作次数 */
private int pCount;
public Worker(int id){
this.id = id;
}
public void run() {
synchronized ("lock") {
for (;;) {
if(count%3==id){
System.out.print(Thread.currentThread().getName());
count++;
pCount++;
"lock".notifyAll();
if(pCount==10)
break;
}else{
try {
"lock".wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args)
{
new Thread(new Worker(0),"A").start();
new Thread(new Worker(1),"B").start();
new Thread(new Worker(2),"C").start();
}