Java - 将等待/通知转换为 java.util.concurrent

标签 java multithreading asynchronous synchronization java.util.concurrent

我很难将带有虚假等待的老式等待通知转换为 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/

相关文章:

java - 这是在 Google Cloud Datastore 中使用 Java 按键查询的正确方法吗?

java - 在Struts 2中实现SessionAware接口(interface)后SessionMap为null

C++类方法线程

asp.net - 检查线程是否仍在运行

c++ - boost ASIO async_read_until 不编译 ASIO ssl 客户端示例

java - 使用 Gson 或 Jackson 将 JSON 字符串扁平化为 Map<String, String>

c++11 使用 std::thread 时意外的多态性行为

javascript - 我应该在 Node.js 和 Express 中链接方法和函数吗?

c# - 字典中存在键时出现 KeyNotFound 异常?

java - 我可以在哪个容器中收集字符串来显示其中的任何一个