用线程池替代Thread,可对线程的创建、销毁、运行进行管理。
1.Runnable
package executor; public class LiftOff implements Runnable { protected int countDown = 10; private static int taskCount = 0; private final int id = taskCount++; private static int count = 0; public LiftOff() { super(); } public LiftOff(int countDown) { this.countDown = countDown; } public String status() { return "#" + id + "(" + (countDown>0 ? countDown : "LiftOff") + "), "; } @Override public void run() { while(countDown-- > 0) { if(++count >= 8) { System.out.println(status()); count = 0; } else { System.out.print(status()); } Thread.yield(); } } }2. 不同的Runnable调用方法
package executor; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.junit.Test; public class ExecutorTest { @Test public void testThread() { for(int i=0; i<5; i++) { new Thread(new LiftOff()).start(); } System.out.print("wating for LiftOff..."); } //在线程数量不够时,动态创建线程 @Test public void testCacheThreadExcutor() { Executor exec = Executors.newCachedThreadPool(); for(int i=0; i<5; i++) { exec.execute(new LiftOff()); } System.out.print("wating for LiftOff..."); } //固定数量线程池,减少线程创建的开销, @Test public void testFixThreadExcutor() { Executor exec = Executors.newFixedThreadPool(5); for(int i=0; i<5; i++) { exec.execute(new LiftOff()); } System.out.print("wating for LiftOff..."); } //线程数量为1,多个任务排队执行 @Test public void testSingleThreadExcutor() { Executor exec = Executors.newSingleThreadExecutor(); for(int i=0; i<5; i++) { exec.execute(new LiftOff()); } System.out.print("wating for LiftOff..."); } }
原文:http://blog.csdn.net/y172158950/article/details/19828835