有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC…
package com.thread;
public class TestWork implements Runnable {
int index;
int pCount;
static int count = 0;
static Object lock = new Object();
public TestWork(int index)
{
this.index=index;
}
public void run() {
synchronized (lock) {
for(;;)
{
if(count%3==index)
{
System.out.println(Thread.currentThread().getName());
count++;
pCount++;
lock.notifyAll();
if(pCount==10)
{
break;
}
}
else
{
try {
lock.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new TestWork(0),"A").start();
new Thread(new TestWork(1),"B").start();
new Thread(new TestWork(2),"C").start();
}
}