我正在尝试编写一个具有多个线程的 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/