gpt4 book ai didi

java - 同一对象上的同步块(synchronized block)是否真的阻止其他线程执行该 block ?

转载 作者:行者123 更新时间:2023-11-30 04:00:16 24 4
gpt4 key购买 nike

嗨,我试图理解等待通知,我在代码中看到了这种行为,即两个线程在同一对象上的同步块(synchronized block)内打印语句。

public class WaitNotifyExample {

/**
* @param args
*/
public static void main(String[] args) {
Message msg = new Message("process it");
Waiter waiter = new Waiter(msg);
new Thread(waiter,"waiter").start();

Waiter waiter1 = new Waiter(msg);
new Thread(waiter1, "waiter1").start();

Notifier notifier = new Notifier(msg);
new Thread(notifier, "notifier").start();
//System.out.println("All the threads are started");

}

}

class Message {
private String msg;

public Message(String str){
this.msg=str;
}

public String getMsg() {
return msg;
}

public void setMsg(String str) {
this.msg=str;
}

}

class Waiter implements Runnable{

private Message msg;

public Waiter(Message m){
this.msg=m;
}

@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (msg) {
try{
System.out.println(name+" waiting to get notified at time:"+System.currentTimeMillis());
msg.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(name+" waiter thread got notified at time:"+System.currentTimeMillis());
//process the message now
System.out.println(name+" processed: "+msg.getMsg());
}
}

}
class Notifier implements Runnable {

private Message msg;

public Notifier(Message msg) {
this.msg = msg;
}

@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(name+" started");
try {
Thread.sleep(1000);
synchronized (msg) {
msg.setMsg(name+" Notifier work done");
//msg.notify();
msg.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

}

这是程序的输出:

    -waiter waiting to get notified at time:1393849891481      -notifier started      -waiter1 waiting to get notified at time:1393849891483      -waiter1 waiter thread got notified at time:1393849892483      -waiter1 processed: notifier Notifier work done      -waiter waiter thread got notified at time:1393849892483  waiter processed: notifier Notifier work done

最佳答案

阅读有关 Object.wait 的 Javadoc:

The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor

当线程在 msg.wait 内阻塞时,它不拥有 msg 的监视器。任何其他线程都可以自由获取它。

关于java - 同一对象上的同步块(synchronized block)是否真的阻止其他线程执行该 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22147265/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com