Java线程2-4 单任务线程池SingleThreadPool

来源:互联网 发布:专业排版设计软件 编辑:程序博客网 时间:2024/06/06 23:58
package thread_threadpool;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.TimeUnit;/** * 单线程任务的线程池 * 好处:当池中的线程死掉了,会再创建一个线程出来继续执行,保证总是有一个线程在执行。 *  * 如果实现线程死后重新启动?---->创建单一线程池 * @author Administrator * */public class ThreadPool_SingleThreadPool {public static void main(String[] args) throws InterruptedException {//定义一个单线程任务的线程池ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();//执行线程for (int i = 0; i < 5; i++) {MyThread3 t = new MyThread3();singleThreadPool.execute(t);Thread.sleep(500);}}}class MyThread3 implements Runnable{<span style="white-space:pre"></span>@Overridepublic void run() {<span style="white-space:pre"></span>System.out.println("当前线程:"+Thread.currentThread().getName());}


执行结果:

当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1
当前线程:pool-1-thread-1

0 0
原创粉丝点击