我很难将带有虚假等待的老式等待通知转换为 java.util.concurrent API
第一个问题:根据 this 使用什么,Future 或 CountdownLatch 或 CyclicBarrier问题
第二个问题:如何使用?因为在我看过的所有示例中,都将单个异步方法转换为同步,这不是问题
第三:在我的情况下, future 任务的 get 方法,CountDownLatch 或 CyclicBarrier 的最佳选择是什么,因为我没有多个线程,但只有 2 个。
我的异步代码
主类:
public static void main(String[] args) throws InterruptedException {
Request req = new Request(1);
Thread tReq = new Thread(req);
tReq.start();
synchronized(req){
req.wait();
}
LogProperties.log.info("Response is: " + req.responseString);
}
请求类:
public class Request implements Runnable {
private int requestID;
public boolean isComplete;
public String responseString;
public Request(int id) {
this.requestID = id;
}
@Override
public void run() {
FutureTest.hmTest.put(requestID, this);
try {
//simulate a request
Thread.sleep(10000);
} catch (InterruptedException ex) {
}
Response response = new Response(requestID);
Thread tResponse = new Thread(response);
tResponse.start();
}
响应类:
public class Response implements Runnable {
int id;
public Response(int responseId) {
this.id = responseId;
}
@Override
public void run() {
Request req = (Request) FutureTest.hmTest.get(id);
req.isComplete = true;
req.responseString = "Request for id [" + id + "] has been completed";
synchronized(req){
req.notify();
}
}
我使用 future callable 和 CyclicBarrier 的问题是我没有返回变量,我想等待一个对象,在这种情况下是 Request 类型,那么最好的解决方案是什么
最佳答案
线程通信最通用的方法之一是 BlockingQueue
。
在您的情况下,您有一个创建“响应”的线程(即 生产者),并且您有另一个线程正在等待“响应”(消费者)。一种实现方法是生产者将响应put()
放入 BlockingQueue,并让消费者take()
将响应从队列中取出。
take()
操作将隐式等待响应可用,然后再返回。
关于Java - 将等待/通知转换为 java.util.concurrent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28041799/