本文主要是介绍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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!