gpt4 book ai didi

java - 同步方法 - 这是如何工作的?

转载 作者:行者123 更新时间:2023-11-29 03:34:31 26 4
gpt4 key购买 nike

我最近看到了下面的一个例子。我无法理解主线程和乘客线程如何同时保留在同步块(synchronized block)中?

public class bus 
{
public static void main(String[] args) throws InterruptedException
{
passenger p = new passenger();
p.start();
synchronized (p)
{
System.out.println("passenger is waiting for the bus, i am in synchronised method");
p.wait();
System.out.println("passenger got notification");
}
System.out.println("after "+p.total+" time");
}
}

class passenger extends Thread
{
int total = 0;

public void run()
{
synchronized (this)
{
System.out.println("wait .... i am in synchronised method");
for (int i = 0; i <= 1000; i++)
total = total + i;
System.out.println("passenger is given notification call");
notify();
}
}
}

这个程序的输出是

passenger is waiting for the bus i am in synchronised method
wait .... i am in synchronised method
passenger is given notification call
passenger got notification
after 500500 time

这意味着当主线程打印出“乘客正在等待我在同步方法中的公共(public)汽车”时,它已经在同步块(synchronized block)中等待。打印的下一条语句是“等待......我在同步方法中”,这意味着乘客线程也进入了它的同步块(synchronized block)。请记住,两个同步块(synchronized block)都具有相同的对象 - p 作为 block 对象。这似乎令人困惑,因为我知道当主线程进入 synchronized(p) block 时,主线程必须阻塞对象 p 并且根据定义没有其他线程可以访问或进入对象 p!

的任何同步块(synchronized block)或方法

最佳答案

How can the main and passenger threads remain in a synchronized block at once?

p.wait() 释放 p 上的锁直到线程重新唤醒,因此任意数量的线程都可以p 上同步,只要最多一个不在等待。

来自 Object's javadoc :

public final void wait() throws InterruptedException

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

关于java - 同步方法 - 这是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16244107/

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