[英]I hava five threads in java server, how should I do to make them run one task concurrently?
I write a web server in java, and need a task class to upload data to anther server, so I do this as below: 我用Java编写了一个Web服务器,并且需要一个任务类将数据上传到另一个服务器,所以我这样做如下:
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5)
executor.scheduleAtFixedRate(new Task(), 0, 100, TimeUnit.SECOND);
The Task
has implement Runnable
. 该
Task
已实现Runnable
。 The question is,every time only one thread is scheduled to run this new Task()
, others just idle, if a large number of data coming, my work queue which store data become very large, more worse, I can't get real time data in anther server. 问题是,每次只有一个线程被调度运行此
new Task()
,其他线程才处于空闲状态,如果有大量数据传入,则存储数据的工作队列变得非常大,更糟糕的是,我无法获得真实的花药服务器中的时间数据。 My English is too bad, I am wandering if you have my got my point, I want to find a way to fix this, can you help me ? 我的英语太糟糕了,如果您明白我的意思,我在徘徊,我想找到一种解决办法,您能帮我吗?
To run 5 tasks at once you need 5 tasks which take long enough that different threads will be used. 要一次运行5个任务,您需要5个任务,这些任务需要很长的时间才能使用不同的线程。 If you add one task, it will use one thread.
如果添加一个任务,它将使用一个线程。 If you add 5 small tasks, they might be all run by the same thread.
如果添加5个小任务,它们可能全部由同一线程运行。
Have you tried this? 你有尝试过吗?
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5);
Task task=new Task();
executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.SECOND);
executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.SECOND);
executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.SECOND);
executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.SECOND);
executor.scheduleAtFixedRate(task, 0, 100, TimeUnit.SECOND);
in this way you will have Only one task scheduled to run in 5 threads. 这样,您将只有一个任务计划在5个线程中运行。 just make sure you have Task
thread safe
(as you will be running same task within 5 threads). 只要确保您具有Task
thread safe
(因为您将在5个线程中运行同一任务)即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.