gpt4 book ai didi

java - 访问线程池运行的对象

转载 作者:行者123 更新时间:2023-12-01 15:10:11 25 4
gpt4 key购买 nike

对于我的程序,我使用 ConcurrentHashMap 来保存对多个正在运行的对象的引用。在我的服务器中我有:

public class Server {

private ConcurrentHashMap<String, ChatRoom> _chatRooms;
private ExecutorService _chatRoomExecutor;
...

// create a new channel executor to handle 50 chatrooms
_chatRoomExecutor= Executors.newFixedThreadPool(50);
// create an admin chatroom for testing at this point
_chatRooms.put("/admin", new Channel("/admin"));
// execute that chatroom
_chatRoomExecutor.execute(_chatRooms.get("/admin"));

这是否有效,因为我仍然可以从 ConcurrentHashMap 访问聊天室,或者我是否必须对线程池执行某些操作?

最佳答案

would this work as I could still access the chatroom from the ConcurrentHashMap or would I have to do something with the threadpool?

是的,你的代码应该可以正常工作。 但是,您需要确保您的 ChatRoom 对象中的字段正确同步,因为它们都可以从其 访问>run() 方法由线程池线程以及外部线程通过从 ConcurrentHashMap 获取对象来实现。这将是你的挑战。

关于java - 访问线程池运行的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12431639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com