java 執行緒 (二) 執行緒池
阿新 • • 發佈:2018-12-27
package cn.sasa.demo2; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Test { public static void main(String[] args) { /** * 執行緒狀態 * Thread.State * * NEW * 至今尚未啟動 new ...() * * RUNNABLE * 正在執行 start() * * BLOCKED * 受阻塞 並 等待某個監視器鎖 * * WAITING * 無限期等待另一個執行緒來執行某一特定操作的執行緒 * wait() 等待 notify()喚醒 * * TIMED_WAITING * 等待另一執行緒來執行,有等待時限 休眠 sleep() * * TERMINATED * 已退出---- run()結束 / stop() 已過時 * * 受阻塞:執行緒具有CPU的執行資格,等CPU的資源 * 休眠等待:執行緒放棄CPU的執行資格 * * 執行緒池 * 從jdk5之後內建執行緒池 * * 1、使用工廠類Executors 中的靜態方法建立執行緒物件,指定執行緒的個數 * 2、呼叫newFixedThreadPool 返回執行緒池物件 ExecutorService **/ ExecutorService es = Executors.newFixedThreadPool(2); es.submit(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName() + "...hello"); } }); es.submit(new Runnable() { publicvoid run() { System.out.println(Thread.currentThread().getName() + "...abc"); } }); es.submit(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName() + "...hahaha"); } });//shutdown 銷燬執行緒池,不常用,因為建立執行緒池就是為了執行緒不被銷燬 //es.shutdown(); for(int i=0; i<100; i++) { System.out.println(i); } } }