1. 程式人生 > >記錄一個基礎執行緒的建立

記錄一個基礎執行緒的建立

執行緒池負責管理工作執行緒,包含一個等待執行的任務佇列。執行緒池的任務佇列是一個Runnable集合,工作執行緒負責從任務佇列中取出並執行Runnable物件。下面是一個簡單示例:

首先建立一個Runable 類:

public class ThreadPoolTest extends Thread{


    //寫一個類執行十次隨機時間休眠
    @Override
    public void run() {
        try {
            for (int i = 0; i < 10; i++) {
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("當前執行緒是  " + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    /**
     * 建立基礎執行緒
     */
    static void newThread() {
        try {
            ThreadPoolTest thread = new ThreadPoolTest();
            thread.setName("new Thread");
            thread.start();
            for (int i = 0; i < 10; i++) {
                final int index = i;
                int time = (int) (Math.random() * 1000);
                Thread.sleep(time);
                System.out.println("當前執行緒是  " + Thread.currentThread().getName());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
public static void main(String[] args) {
    newThread();
}

}

輸出結果:

當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  new Thread
當前執行緒是  new Thread
當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  main
當前執行緒是  main
當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  main
當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  new Thread
當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  main
當前執行緒是  new Thread
當前執行緒是  new Thread
當前執行緒是  main