日期:2014-05-20 浏览次数:20691 次
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Ex3 { public static void main(String[] args) { System.out.println("------Cached Pool------"); ExecutorService execCached = Executors.newCachedThreadPool(); execCached.execute(new Imex31()); execCached.execute(new Imex32()); execCached.execute(new Imex33()); execCached.shutdown(); System.out.println("------Fixed Pool------"); ExecutorService execFixed = Executors.newFixedThreadPool(3); execFixed.execute(new Imex31()); execFixed.execute(new Imex32()); execFixed.execute(new Imex33()); execFixed.shutdown(); System.out.println("------Single Thread------"); ExecutorService execSingle = Executors.newSingleThreadExecutor(); execSingle.execute(new Imex31()); execSingle.execute(new Imex32()); execSingle.execute(new Imex33()); execSingle.shutdown(); /*Thread t1 = new Thread(new Imex31()); Thread t2 = new Thread(new Imex32()); Thread t3 = new Thread(new Imex33()); t1.start(); t2.start(); t3.start();*/ } } class Imex31 implements Runnable { public Imex31() { System.out.println("Constructor 1 begin"); } public void run() { for (int i = 1; i < 4; i++) { System.out.println("In the run ex1 " + i); Thread.yield(); } System.out.println("ex1 complete"); return; } } class Imex32 implements Runnable { public Imex32() { System.out.println("Constructor 2 begin"); } public void run() { for (int i = 1; i < 4; i++) { System.out.println("In the run ex2 " + i); Thread.yield(); } System.out.println("ex2 complete"); return; } } class Imex33 implements Runnable { public Imex33() { System.out.println("Constructor 3 begin"); } public void run() { for (int i = 1; i < 4; i++) { System.out.println("In the run ex3 " + i); Thread.yield(); } System.out.println("ex3 complete"); return; } }