标签:
一、固定大小的线程池,newFixedThreadPool:
package Executor.test; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorTest { public static void main(String[] args) { // TODO Auto-generated method stub doExecutor(); } static void doExecutor() { //create reuse,fix number,thread pool ExecutorService pool = Executors.newFixedThreadPool(5); //create threads Thread t1 = new Thread(new MyThread()); Thread t2 = new Thread(new MyThread()); Thread t3 = new Thread(new MyThread()); Thread t4 = new Thread(new MyThread()); Thread t5 = new Thread(new MyThread()); //execute thread in thread pool pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //shutdown thread pool pool.shutdown(); } static class MyThread implements Runnable { @Override public void run() { // TODO Auto-generated method stub System.out.println("running thread:"+Thread.currentThread().getName()); } } }
执行结果:
running thread:pool-1-thread-1
running thread:pool-1-thread-3
running thread:pool-1-thread-5
running thread:pool-1-thread-2
running thread:pool-1-thread-4
改变线程池的大小:
ExecutorService pool = Executors.newFixedThreadPool(3)
执行结果:
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-2
running thread:pool-1-thread-3
结论:从以上结果可以看出,newFixedThreadPool的参数指定了可以运行的线程的最大数目,超过这个数目的线程加进去以后,不会运行。其次,加入线程池的线程属于托管状态,线程的运行不受加入顺序的影响。
二、单任务线程池,newSingleThreadExecutor:
ExecutorService pool = Executors.newSingleThreadExecutor();
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
running thread:pool-1-thread-1
Android(Java)线程池:ExecutorService和Executors使用(二)
标签:
原文地址:http://www.cnblogs.com/Android9527/p/5406957.html