建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。
/*
* 建立三个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC。
*/
class Demo implements Runnable {
int count = 10;
String name;
Object pre;
Object self;
public Demo(String name, Object pre, Object self) {
super();
this.name = name;
this.pre = pre;
this.self = self;
}
@Override
public void run() {
while (count > 0) {
synchronized (pre) {
synchronized (self) {
System.out.print(name);
count--;
self.notify();
}
try {
pre.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Test3 {
public static void main(String[] args) throws InterruptedException {
Object a = new Object();
Object b = new Object();
Object c = new Object();
Demo d1 = new Demo("A", c, a);
Demo d2 = new Demo("B", a, b);
Demo d3 = new Demo("C", b, c);
new Thread(d1).start();
Thread.sleep(100);
new Thread(d2).start();
Thread.sleep(100);
new Thread(d3).start();
Thread.sleep(100);
}
}