gpt4 book ai didi

java - 同步方法 block 执行

转载 作者:行者123 更新时间:2023-11-30 02:24:50 26 4
gpt4 key购买 nike

我正在实现一个包含三个类的虚拟程序,以便更直观地了解 Future 的工作原理。我的问题是,有时程序会被锁定在同步方法上,并且无法继续。而且我找不到原因。有人能找出为什么没有一个战士会打印“我赢了”这行字的原因吗?

阻塞时我当前的输出:

Fighter1

Fighter1 has entered the sync method

Fighter2

Fighter2 has entered the sync method

代码如下。

主类:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TmpTest {
private static final ExecutorService executorService =
Executors.newFixedThreadPool(2);

public static void main(final String... args) {

final Fighter fighter1 = new Fighter("Fighter1");
final Fighter fighter2 = new Fighter("Fighter2");

final Future<String> submitFighter1 = executorService.submit(fighter1);
final Future<String> submitFighter2 = executorService.submit(fighter2);

while (!submitFighter1.isDone() || !submitFighter2.isDone()) {
if (submitFighter1.isDone()) {
System.out.println("Fighter 1 wins!");
submitFighter2.cancel(true);
executorService.shutdown();
} else if (submitFighter2.isDone()) {
submitFighter1.cancel(true);
System.out.println("Fighter 2 wins!");
executorService.shutdown();
}
}
}
}

战斗机类别:

class Fighter implements Callable<String> {

private final String fighterName;
private final ClassWithSyncMethod classWithSyncMethod;

public Fighter(final String fighterName) {
this.fighterName = fighterName;
classWithSyncMethod = new ClassWithSyncMethod(fighterName);
}

@Override
public String call() throws Exception {
return classWithSyncMethod.syncMethod();
}
}

具有同步方法的虚拟类:

class ClassWithSyncMethod {

private final String fighterName;

public ClassWithSyncMethod(final String fighterName) {
this.fighterName = fighterName;
}

public synchronized String syncMethod() {
System.out.println(fighterName + " has entered the sync method");
try {
Thread.sleep(1000);
} catch (final InterruptedException e) {
System.out.println("Exception trying to sleep the fighter " + fighterName + ";" + e);
}
return fighterName + " shouts: I won!";
}
}

最佳答案

这与同步无关。每个战斗机在不同的对象上同步,因此它们不会互相干扰。

您看不到“我赢了”行的原因要简单得多 - 您从不打印它。ClassWithSyncMethod#syncMethod() 方法(由 Fighter#call() 返回)不会打印任何内容,它只是返回一个值。如果您想打印它,您必须自己从 main 中执行此操作。

例如:

while (!submitFighter1.isDone() || !submitFighter2.isDone()) {
if (submitFighter1.isDone()) {
System.out.println("Fighter 1 wins!");
System.out.println(submitFighter1.get()); // Here!
submitFighter2.cancel(true);
executorService.shutdown();
} else if (submitFighter2.isDone()) {
submitFighter1.cancel(true);
System.out.println("Fighter 2 wins!");
System.out.println(submitFighter2.get()); // And here!
executorService.shutdown();
}
}

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

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