gpt4 book ai didi

java - 锁定java同步方法

转载 作者:行者123 更新时间:2023-11-29 05:51:11 25 4
gpt4 key购买 nike

我正在尝试使用同步方法编写一个带有线程的 Java 程序。但是我无法理解当另一个线程调用 java 中的同步方法时,我如何显示一个线程已经在运行。谁能用简单的例子解释一下

最佳答案

这是一个人为的例子,它显示了交织和阻塞过程。在我的机器上打印:

Thread[Thread-0,5,main] is going to call the synchronized method
Thread[Thread-1,5,main] is going to call the synchronized method
Thread[Thread-0,5,main] is in the synchronized method
Thread[Thread-0,5,main] is exiting the method
Thread[Thread-1,5,main] is in the synchronized method
Thread[Thread-1,5,main] is exiting the method

可以看到只有一个线程进入了同步块(synchronized block),而另一个在等待。

public class Test1 {

public static void main(String[] args) throws Exception {
final Test1 test = new Test1();
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread() + " is going to call the synchronized method");
test.method();
}
};
new Thread(r).start();
new Thread(r).start();
}

public synchronized void method() {
System.out.println(Thread.currentThread() + " is in the synchronized method");
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
System.out.println(Thread.currentThread() + " is exiting the method");
}
}

关于java - 锁定java同步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13796961/

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