java - 与并发共享变量

标签 java multithreading concurrency

我正在尝试编写一个具有多个线程的 Java 程序。我有两个在启动时创建的变量。一个是 AtomicBoolean,它告诉整个程序何时关闭(即关闭客户端)。另一个变量是 ConcurrentHashMap,它包含一组在启动时加载的命令。有些线程包含一个客户端可运行的线程,当客户端被接受时运行(每个客户端一个线程)。还有一个线程通过监听外部变化(来自目录的新命令等)将命令更新到 HashMap

代码如下:

class Program {
    /* ... other vars like ServerSocket, etc. */
    private final ConcurrentHashMap<String, String> mCommands;
    private final AtomicBoolean mIsListening;

    public static void main(String[] args) {
        Program prog = new Program();
        prog.loadCommands();
        prog.listen();
    }

    public Program() {
        mCommands = new ConcurrentHashMap<>();
        mIsListening = new AtomicBoolean(true);
        /* other initializations */
    }

    public void loadCommands() {
         /* Loads commands generated from a directory; updates mCommands, then... */
         new Thread(new CommandListenerRunnable(mCommands)).start();
    }

    public void listen() {
        /* accepting a new client from server socket */
        while (mIsListening.get()) {
            Socket client = ss.accept();
            new Thread(new ClientRunnable(client, mCommands, mIsListening)).start();
        }
    }
}

如您所见,对于我创建的每个 child ,我都将这些变量作为参数传递。总而言之,这是分配这些变量的正确方法吗?任何想法将不胜感激。提前致谢!

最佳答案

我认为这个设计很好,因为每个线程都应该有一份它需要的变量。

你说:

For instance, I can use map.putIfAbsent() to make the operation be performed atomically

但这并不能使您的 map 线程安全,因为有人可以在上面调用其他东西。

关于java - 与并发共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41254738/

相关文章:

sorting - Golang - 按扇形排序

java - 从 Spring 支架 Controller 返回带有查询参数的响应

同步、 volatile 和(标记)锁的 Java 内存模型交互

concurrency - Golang - 为什么会出现这种竞争情况?

java - 在 Timer.Schedule() 中抛出空指针异常;

将纳秒转换为微秒

java - volatile 数组的奇怪行为

java - 如何自动使用m2e在eclipse中配置checkstyle?

java - WAR 中的无状态 ejb > 打包到 EAR > 本地 ejb 调用

java - 如何创建在固定时间间隔内触发一次且仅触发一次的流式Beam管道