gpt4 book ai didi

java - 同步并通知执行顺序和范围

转载 作者:行者123 更新时间:2023-12-03 21:00:49 27 4
gpt4 key购买 nike

1)线程是否在该线程同步代码块中调用通知后立即放弃它的锁定,或者一旦退出同步代码块?

例如,似乎没有指定线程优先级,我的 Process 类将自上而下执行。 Produce 将首先被调用,它会做一些事情,然后 wait();消费将运行,然后它点击通知(),它将打印“完成”或者会先有 5 秒的延迟,然后会打印“完成”?

2)另外,如果我有第三个同步方法/线程,它不等待或通知而只是运行,我可以预测我的操作执行的顺序吗?

3) 最后,notify() 如何知道要“唤醒”哪个线程?比如,假设我有多个进程,每个进程同时执行 2 个线程,每个进程 A、B 和 C 调用 notify()。每个 notify() 是每个 Process 本地的吗?换句话说,如果进程 A 调用 notify(),那能唤醒进程 B 中的等待线程吗?到目前为止,我已经看到同步调用(this),这让我认为它引用了一个特定的对象类,这反过来又让我认为在同步块(synchronized block)中调用的所有 notify() 都受同步( this) 指的是,所以不会有交叉。

public class Process {

public void produce( ) {
synchronized(this) {
// do stuff
wait( );
System.out.println("Done");
}
}


public void consume( ) {
synchronized(this) {
// stuff
notify();
Thread.sleep(5000);
}
}
}

最佳答案

您可以编写一个简单的程序来测试它

public static void main(String[] args) throws Exception {
final Process e = new Process();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
e.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
e.produce();
}

该程序等待 5000 毫秒并打印
Done

至于你的问题

1) Does a thread relinquish it's lock as soon as notify is invoked within that threads synchronized code block, or once the synchronized code block is exited?


notify() 的 javadoc状态

If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.**strong text A thread waits on an object's monitor by calling one of the wait methods.

The awakened thread will not be able to proceed until the current thread relinquishes the lock on this object



所以,不,线程在调用 notify() 时不会放弃对锁的控制。 .这将在代码退出 synchronized 时发生。堵塞。

2) Also, if I had a third synchronized method/thread, that does not wait or notify and just runs, can I predict the order in which my operations are executed a priori?



你可以估计,但不能确定。执行由线程调度程序自行决定。

3) Finally, how does notify() know what thread to 'wake up'?



电话不知道。线程调度程序知道并选择。你无法控制这一点。
wait() 的 javadoc和 notify()状态

This method should only be called by a thread that is the owner of this object's monitor.





IllegalMonitorStateException - if the current thread is not the owner of this object's monitor.



因此,您只能在位于 synchronized 内的对象上调用它们。在该对象上同步的 block 。

在您的代码示例中,调用
wait();

隐含地在做
this.wait();

关于java - 同步并通知执行顺序和范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20510102/

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