Java 使用ThreadPoolExecutor()只运行一个线程
我使用ThreadPoolExecutor()为我的应用程序运行多个线程。我想用单线程进行测试,所以在本例中,我将nb_threads设置为1。但我不确定它是否正确,所以你能帮我只取一根线吗 这是我的部分代码:Java 使用ThreadPoolExecutor()只运行一个线程,java,multithreading,threadpoolexecutor,Java,Multithreading,Threadpoolexecutor,我使用ThreadPoolExecutor()为我的应用程序运行多个线程。我想用单线程进行测试,所以在本例中,我将nb_threads设置为1。但我不确定它是否正确,所以你能帮我只取一根线吗 这是我的部分代码: private ThreadPoolExecutor executor = null; public static int NB_THREADS_MAX = 8; public void submit(Runnable inRunnable) { if (executo
private ThreadPoolExecutor executor = null;
public static int NB_THREADS_MAX = 8;
public void submit(Runnable inRunnable) {
if (executor == null) {
/*Choice exactly the number of threads that relates the number of available processors*/
nb_threads = NB_THREADS_MAX < (tmp = Runtime.getRuntime().availableProcessors())
? NB_THREADS_MAX
: tmp;
executor = new ThreadPoolExecutor(nb_threads, nb_threads, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); /*In this case, the pool size is fixed*/
}
executor.submit(inRunnable);
}
private ThreadPoolExecutor executor=null;
公共静态int NB_线程_MAX=8;
公共作废提交(不可运行){
if(executor==null){
/*选择与可用处理器数相关的线程数*/
nb_threads=nb_threads_MAX<(tmp=Runtime.getRuntime().availableProcessors())
?NB_螺纹_最大值
:tmp;
executor=new ThreadPoolExecutor(nb_threads,nb_threads,0,TimeUnit.ms,new LinkedBlockingQueue());/*在这种情况下,池大小是固定的*/
}
执行人提交(不可更改);
}
为什么不使用factory类,它公开了几种方便的方法
例如:
您可以在单线程池中执行以下操作:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executorService = Executors.newSingleThreadExecutor();
如果您检查newSingleThreadExecutor
源代码,您会发现
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
感谢sfat,我同意Executor比它简单,但我使用ThreadPoolExecutor很长时间了,现在我只想测试单个线程,不想通过其他线程更改任何东西。此外,ThreadPoolExecutor是Executor:)的一个子类。跟着你,我的建议正确吗?@hamalo是的,应该可以。我还编辑了我的答案,向您展示了newSingleThreadExecutor的实现,它将与您所希望的一样,所以快发疯吧。虽然我以后会推荐使用Executors工厂类,因为它帮助很大。非常好!是的,我将来使用Executors工厂类。谢谢你!
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());