我很难将带有虚假等待的老式等待通知转换为java.util.concurrent API。
第一个问题:根据this问题,使用什么,未来、CountdownLatch还是CyclicBarrier
第二个问题:如何使用它?因为在我看过的所有示例中,都是将单个异步方法转换为同步方法,这不是问题
第三:在我的例子中,out 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();
}
}}
我使用将来的callable和CyclicBarrier的问题是,我没有返回变量,我想等待一个对象,在本例中,该对象的类型为Request,那么最好的解决方案是什么
发布于 2015-01-20 22:40:39
最通用的线程通信方式之一是BlockingQueue。
在您的例子中,您有一个创建“响应”的线程(即生产者),还有另一个线程正在等待“响应”(即消费者)。实现这一点的一种方法是,生产者将响应put()到BlockingQueue中,然后让消费者将响应take()出队列。
take()操作将隐式地等待响应变得可用,然后才返回。
发布于 2015-01-20 19:41:31
我认为管道可以很好地解决这个问题,它可以很容易地实现同步通信。
查看针对生产者和消费者问题的管道链接- http://www.informit.com/articles/article.aspx?p=26326&seqNum=10
https://stackoverflow.com/questions/28041799
复制相似问题