建立三个线程A、B、C,A线程打印10次字母A,B线程打印10次字母B,C线程打印10次字母C,但是要求三个线程同时运行,并且实现交替打印,即按照ABCABCABC的顺序打印。
基于 wait,notify
需要注意的点:
- wait和notify都是对象.wait,对象.notify,类似于资源。
- 实现runnable接口。运行时作为构造函数参数: Thread a = new Thread(myRunnable);a.start();
链接中:基于lock(reetranlock)、lock+condition、semphore信号量
多线程交替打印ABC的多种实现方法
代码
public class ABC {
public static class ThreadPrinter implements Runnable {
private String name;
private Object prev;
private Object self;
private ThreadPrinter(String name, Object prev, Object self) {
this.name = name;
this.prev = prev;
this.self = self;
}
@Override
public void run() {
int count = 10;
while(count>0) {// 多线程并发,不能用if,必须使用while循环
synchronized (prev){ // 先获取 prev锁
synchronized (self) {
System.out.println(name);
count--;
self.notifyAll();// 唤醒其他线程竞争self锁,注意此时self锁并未立即释放
}
// 执行完self的同步块,self锁才释放
try {
if (count == 0) {// 如果count==0,表示这是最后一次打印操作,通过notifyAll操作释放对象锁。
prev.notifyAll();
} else {
prev.wait(); // 立即释放 prev锁,当前线程休眠,等待唤醒
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception {
Object a = new Object();
Object b = new Object();
Object c = new Object();
// ThreadPrinter 实现了runnable接口
ThreadPrinter pa = new ThreadPrinter("A",c,a);
ThreadPrinter pb = new ThreadPrinter("B",a,b);
ThreadPrinter pc = new ThreadPrinter("C",b,c);
// 使其运行
Thread at = new Thread(pa);
at.start();
Thread.sleep(10); // 初始启动顺序
new Thread(pb).start();
Thread.sleep(10);
new Thread(pc).start();
Thread.sleep(10);
}
}
}