java - 如何让线程等待直到变量达到特定值(多线程Java)

标签 java multithreading concurrency java.util.concurrent concurrenthashmap

我有一个接受客户端连接的服务器程序。这些客户端连接可以属于许多流。例如,两个或多个客户端可以属于同一个流。在这些流中,我必须传递一条消息,但我必须等到所有流都建立起来。为此,我维护了以下数据结构。

ConcurrentHashMap<Integer, AtomicLong> conhasmap = new ConcurrentHashMap<Integer, AtomicLong>();

Integer 为流 ID,Long 为客户端编号。为了使给定流的一个线程等待 AtomicLong 达到特定值,我使用了以下循环。实际上,流的第一个数据包包含流 ID 和要等待的连接数。对于每个连接,我都会减少要等待的连接数。

while(conhasmap.get(conectionID) != new AtomicLong(0)){
       // Do nothing
}

但是这个循环阻塞了其他线程。根据这个 answer它进行 volatile 读取。如何修改代码以等待给定流的正确线程,直到它达到特定值?

最佳答案

如果您使用的是 Java 8,CompletableFuture 可能是一个不错的选择。这是一个完整的人为示例,它正在等待 5 个客户端连接并向服务器发送消息(使用带有报价/轮询的 BlockingQueue 进行模拟)。

在此示例中,当达到预期的客户端连接消息计数时,CompletableFuture Hook 完成,然后在您选择的任何线程上运行任意代码。

在此示例中,您没有任何复杂的线程等待/通知设置或繁忙的等待循环。

package so.thread.state;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

public class Main {

  public static String CONNETED_MSG = "CONNETED";
  public static Long EXPECTED_CONN_COUNT = 5L;

  public static ExecutorService executor = Executors.newCachedThreadPool();
  public static BlockingQueue<String> queue = new LinkedBlockingQueue<>();

  public static AtomicBoolean done = new AtomicBoolean(false);

  public static void main(String[] args) throws Exception {

    // add a "server" thread
    executor.submit(() -> server());

    // add 5 "client" threads
    for (int i = 0; i < EXPECTED_CONN_COUNT; i++) {
      executor.submit(() -> client());
    }

    // clean shut down
    Thread.sleep(TimeUnit.SECONDS.toMillis(1));
    done.set(true);
    Thread.sleep(TimeUnit.SECONDS.toMillis(1));
    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.SECONDS);

  }

  public static void server() {

    print("Server started up");
    // track # of client connections established
    AtomicLong connectionCount = new AtomicLong(0L);

    // at startup, create my "hook"
    CompletableFuture<Long> hook = new CompletableFuture<>();
    hook.thenAcceptAsync(Main::allClientsConnected, executor);

    // consume messages
    while (!done.get()) {
      try {
        String msg = queue.poll(5, TimeUnit.MILLISECONDS);
        if (null != msg) {
          print("Server received client message");
          if (CONNETED_MSG.equals(msg)) {
            long count = connectionCount.incrementAndGet();

            if (count >= EXPECTED_CONN_COUNT) {
              hook.complete(count);
            }
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    print("Server shut down");

  }

  public static void client() {
    queue.offer(CONNETED_MSG);
    print("Client sent message");
  }

  public static void allClientsConnected(Long count) {
    print("All clients connected, count: " + count);
  }


  public static void print(String msg) {
    System.out.println(String.format("[%s] %s", Thread.currentThread().getName(), msg));
  }
}

你得到这样的输出

[pool-1-thread-1] Server started up
[pool-1-thread-5] Client sent message
[pool-1-thread-3] Client sent message
[pool-1-thread-2] Client sent message
[pool-1-thread-6] Client sent message
[pool-1-thread-4] Client sent message
[pool-1-thread-1] Server received client message
[pool-1-thread-1] Server received client message
[pool-1-thread-1] Server received client message
[pool-1-thread-1] Server received client message
[pool-1-thread-1] Server received client message
[pool-1-thread-4] All clients connected, count: 5
[pool-1-thread-1] Server shut down

关于java - 如何让线程等待直到变量达到特定值(多线程Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28069203/

相关文章:

Java InputStream 无法从 JAR 中读取文件

Java JFace 数据绑定(bind) : Update SWT widget from background thread

c - 可见的副作用顺序

c++ - 为什么在使用 8 个生产者 1 个消费者进行测试时,golang channel 比 intel tbb concurrent_queue 快得多

android - 一遍又一遍地点击主页按钮时,AsyncTask 失步了

Javascript - setTimeout、clearTimeout、setInterval、clearInterval 的替代方法

java - [JWT][JJWT] 函数compact() 非常慢

java - 如何录制 PCM 数小时,但停止时仅保存最后 5 分钟的录音?

linux - 内核代码 wait_event() 和 wake_up() 下系统挂起和 CPU 高

c - 单线程程序是否在多个线程上执行? [C]