import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;java
/** *ide
*/ public class TestThread { public static void main(String args[]){ //建立一個可重用固定線程數的線程池 ExecutorService pool = Executors.newFixedThreadPool(4);線程
//建立一個使用單個 worker 線程的 Executor,以無界隊列方式來運行該線程。
// ExecutorService pool = Executors.newSingleThreadExecutor(); //建立實現了runnable接口的對象 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //將線程放入池中進行執行 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //關閉線程池 pool.shutdown(); } } class MyThread extends Thread{code
@Override public void run(){ System.out.println(Thread.currentThread().getName()+" is running..."); }
}對象
輸出結果: pool-1-thread-1 is running... pool-1-thread-1 is running... pool-1-thread-3 is running... pool-1-thread-2 is running... pool-1-thread-4 is running...接口