線程池的使用步驟:
1.使用Executor裏提供的靜態方法newFixedThreadPool生產一個制定數量的線程池
2.創建一個類,實現Runnable接口。重寫run方法,設置線程任務
3.調用ExecutorService裏的方法submit,傳遞線程任務,開啓線程執行run方法
4.調用ExecutorService裏的方法shotdown銷燬線程池
具體代碼如下:
實現接口的類:
public class RunnableImpl implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" 創建了新的線程任務");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
主程序:
import java.util.concurrent.*;
public class ThreadPool {
public static void main(String[] args) {
ExecutorService es =Executors.newFixedThreadPool(2);//創建一個線程數爲2的線程池
es.submit(new RunnableImpl());
es.submit(new RunnableImpl());
es.submit(new RunnableImpl());
}
}
運行結果: