随笔记录
开启三个线程打印ABC-synchronized锁和wait,notifyAll
2022-3-8 diaba
package com.jiucaiyuan.net.thread;
/**
*
* 题目:
* 编写程序,开启三个线程,这三个线程的ID分别是A,B,C,每个线程将自己的ID在屏幕上打印十次,
* 要求输出结果必须按照ABC的顺序显示,如:ABCABCACB…
*
* 非指定线程唤醒。采用synchronized锁和wait,notifyAll配合使用。
* 这个方法有一个缺点,那就是notifyAll是唤醒其它两个线程,
* 其它两个竞争获取锁会引起上下文切换,从而引起不必要的开销,因此,建议使用方法一。
*
*
*/
class PrintRunnable implements Runnable{
private Object object;
private static volatile String who;
private String next;
public PrintRunnable(Object object, String next){
this.object =object;
this.next=next;
}
@Override
public void run() {
for (int i = 1; i <=10; i++) {
synchronized(object){
while(Thread.currentThread().getName()!= who) {
try {
//需要使用condition调用。
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程"+Thread.currentThread().getName()+" 第"+i+"次打印");
//设置下一个需要打印的线程名
who = next;
//唤醒其它两个线程。
object.notifyAll();
}
}
}

public static void main(String[] args) {
//同步对象,从A开始
Object object=new Object();
PrintRunnable.who = "A";
new Thread(new PrintRunnable(object,"B"),"A").start();
new Thread(new PrintRunnable(object,"C"),"B").start();
new Thread(new PrintRunnable(object,"A"),"C").start();
}
}
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容