java线程池之newSingleThreadExecutor
Posted 胡乐天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程池之newSingleThreadExecutor相关的知识,希望对你有一定的参考价值。
newSingleThreadExecutor测试类
package com.thread.pool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestSingleThreadExecutor {
public static void main(String[] args) {
/**
* FinalizableDelegatedExecutorService
* (new ThreadPoolExecutor(1, 1,
* 0L, TimeUnit.MILLISECONDS,
* new LinkedBlockingQueue<Runnable>()));
*
* 核心线程数为1,最大线程数为1,超出核心线程数的线程(一般来说不会出现超出核心数的线程,具体为啥,请看线程执行任务步骤)的存活时间为0,
* 无边界的队列,会将来到的任务都放到队列中
*
* 此种线程池中只有一个线程,这样会保证顺序的执行各个按照时间到达的任务。
*/
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i=0; i<10; i++){
Thread thread = new Thread(new ThreadPool("" + i));
executorService.execute(thread);//会看到是按顺序执行的,name=1到name=9
}
executorService.shutdown();
}
}
线程任务测试类
package com.thread.pool;
import java.util.Date;
public class ThreadPool implements Runnable {
private static ThreadPool threadPool = null;
String name;
public ThreadPool(String name){
this.name = name;
}
@Override
public void run() {
doSomeThing();
}
public static synchronized Runnable getInstance(){
if(threadPool == null){
threadPool = new ThreadPool("getInstance");
}
return getInstance();
}
private void doSomeThing() {
for (int i=0;i<10;i++){
System.out.println((new Date()).toLocaleString() + " " + Thread.currentThread().getName() + "执行" +i + ",name=" + name);
}
/* try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
}
以上是关于java线程池之newSingleThreadExecutor的主要内容,如果未能解决你的问题,请参考以下文章