标签:style blog http color os java io ar art
首先来说一说java连接池中常用到的几个类:Executor,ExecutorService,ScheduledExecutorService
执行已经提交的Runnable任务对象。此接口提供了将任务提交和任务执行分离的机制。
它是Executor的子接口,可以终止提交新的线程任务,可以中式线程池里现有的所有线程,还可以批量提交线程任务等。它的方法有很多,可以详细阅读相关的api。
可延时执行线程任务
本文中案例中的线程实现如下:
public class ThreadDemo implements Runnable{ private String threadName = null; private boolean flag = true; private int count; private int counter; private long suspend; /** * This is the constructor * @param threadName * @param count 循环次数 * @param suspend 线程终端时间,单位毫秒 */ public ThreadDemo(String threadName, int count, long suspend) { super(); this.threadName = threadName; this.count = count; this.suspend = suspend; } /** * run */ @Override public void run() { while (flag) { try { Thread.sleep(suspend); System.out.println(threadName+"--------------"+counter); counter++; if(counter>count){ flag = false; } } catch (InterruptedException e) { e.printStackTrace(); } } } }
ExecutorService executorService1 = Executors.newCachedThreadPool(); executorService1.execute(new ThreadDemo("线程B-1", 5, 200)); executorService1.execute(new ThreadDemo("线程B-2", 5, 200)); executorService1.shutdown(); executorService1.shutdown()作用是拒绝接收其它的线程,在线程池里的线程都执行完后,关闭线程池。
ExecutorService executorService1 = Executors.newFixedThreadPool(2); executorService1.submit(new ThreadDemo("线程B-1", 5, 200)); executorService1.submit(new ThreadDemo("线程B-2", 5, 200)); executorService1.submit(new ThreadDemo("线程B-3", 5, 200)); executorService1.shutdown(); 这里创建的线程池大小为2,若是提交的线程个数大于2,多余的则会在队列里等候
ExecutorService executorService1 = Executors.newSingleThreadExecutor(); executorService1.execute(new ThreadDemo("线程A-1", 5, 200)); executorService1.execute(new ThreadDemo("线程A-2", 5, 200)); executorService1.shutdown(); 可提交多个线程,但一次只运行一个线程,其它的在队列里等待
ScheduledExecutorService executorService1 = Executors.newScheduledThreadPool(2); executorService1.schedule(new ThreadDemo("线程B-1", 5, 500),1,TimeUnit.SECONDS); executorService1.schedule(new ThreadDemo("线程B-2", 5, 500),2,TimeUnit.SECONDS); executorService1.schedule(new ThreadDemo("线程B-3", 5, 500),3,TimeUnit.SECONDS); executorService1.shutdown();
关于Executors.newScheduledThreadPool(int corePoolSize)中的corePoolSize:当提交一个任务到线程池时,线程池会创建一个线程来执行任务,即使其他空闲的基本线程能够执行新任务也会创建线程,等到需要执行的任务数大于线程池基本大小时就不再创建。如果调用了线程池的prestartAllCoreThreads方法,线程池会提前创建并启动所有基本线程。
ScheduledExecutorService executorService1 = Executors.newSingleThreadScheduledExecutor(); executorService1.schedule(new ThreadDemo("线程A-1", 5, 500),1,TimeUnit.SECONDS); executorService1.schedule(new ThreadDemo("线程A-2", 5, 500),2,TimeUnit.SECONDS); executorService1.shutdown();
每个类有什么方法,看具体的api,以上只是语法范例。
标签:style blog http color os java io ar art
原文地址:http://www.cnblogs.com/leocook/p/java_threadpool.html