gpt4 book ai didi

java - 延迟异步返回 - IllegalMonitorStateException

转载 作者:行者123 更新时间:2023-12-03 12:59:08 24 4
gpt4 key购买 nike

我正在尝试在新线程中调用方法,该方法将在使用 callable 延迟后返回一些东西。由于,它正在下降IllegalMonitorStateException
当我只创建类的实例,调用方法并且该方法将延迟返回对象时,是否可以以这种方式封装线程服务?
先感谢您。

// ENTITY
public class Result {
public String name;
public int value;

public Result(String name, int value) {
this.name = name;
this.value = value;
}

public Result() {
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "Result{" +
"name='" + name + '\'' +
", value=" + value +
'}';
}
}

创建具有延迟和返回值的线程
import java.util.concurrent.*;

public class AsyncCallable {

public Result calculate() throws ExecutionException, InterruptedException {

int delay = 5000;
ExecutorService executorService = Executors.newSingleThreadExecutor();

Callable<Result> callable = () -> {
this.wait(delay);
return new Result("Name", 4);
};

Future<Result> future = executorService.submit(callable);
executorService.shutdown();
return future.get();
}

}

调用方式:
import java.util.concurrent.ExecutionException;

public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {

AsyncCallable asyncCallable = new AsyncCallable();

System.out.println(asyncCallable.calculate().toString());


}
}

最佳答案

好吧,要坚持您的情况,对 wait() 的任何调用都必须包含在同步块(synchronized block)中(请参阅方法 javadoc here )。但是,我认为您应该考虑使用内置工具,例如 Scheduled thread pool .使用它,您可以执行以下操作:

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Executors;

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(4);
// Execute a task after 5 seconds
scheduler.schedule(() -> new Result("Name", 4), 5, TimeUnit.SECONDS);

关于java - 延迟异步返回 - IllegalMonitorStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858292/

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