[英]ConcurrentLinkedQueue usage with multithreading
作为我项目的一部分,我需要创建一个包含固定线程数的线程池。每当线程分配给不同的进程时,我也需要与线程一起分配那么多会话。我想使用ConcurrentLinkedQueue(大小)以存储会话,以便在线程完成后将会话放回Queue中,以供其他进程使用。希望我的要求已明确...任何人都可以给我一些魁德从如何实现开始..?如何使用ConcurrentLinkedQueue ..?
I assume you want to do the same thing as 我假设您想做与
Executors.newFixedThreadPool(n);
It not clear why you don't just use this thread pool. 还不清楚为什么您不只是使用此线程池。
It appears also you want to use a Queue as an object pool. 您似乎还想使用队列作为对象池。 You can use
add()
to and poll()
to see if a free element is available. 您可以使用
add()
和poll()
来查看空闲元素是否可用。
when ever the threads are allocated to different processes ...
每当线程分配给不同的进程时...
You won't be able to share resources between threads in different processes with a ConcurrentLinkedQueue. 使用ConcurrentLinkedQueue,您将无法在不同进程中的线程之间共享资源。 It will be only accessible from the threads of one process.
它只能从一个进程的线程访问。
If this is not the problem you can use a thread pool : 如果这不是问题,则可以使用线程池 :
Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory)
A ThreadFactory can associate the Session resource with the threads managed by the thread pool using a ThreadLocal . ThreadFactory可以使用ThreadLocal将Session资源与线程池管理的线程相关联。 You can configure different initialization strategies.
您可以配置不同的初始化策略。 Don't forget to clean up the sessions when the thread pool shuts down.
不要忘记在线程池关闭时清理会话。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.