2017年計算機二級考試java章節(jié)輔導(dǎo):多線程例子

字號:


    7.2.2 多線程例子
    下面這個例子創(chuàng)建了三個單獨的線程,它們分別打印自己的“Hello World":
    //Define our simple threads.They will pause for a short time
    //and then print out their names and delay times
    public class TestThread extends Thread {
    private String whoami; //定義其屬性
    private int delay;
    //Our constructor to store the name (whoami)
    //and time to sleep (delay)
    public TestThread(String s, int d) { //定義了一個線程的構(gòu)造函數(shù)
    whoami = s;
    delay = d;
    }
    //Run - the thread method similar to main()
    //When run is finished, the thread dies.
    //Run is called from the start() method of Thread
    public void run() { //運行線程
    //Try to sleep for the specified time
    try {
    sleep(delay); //讓線程進行睡眠
    }
    catch(InterruptedException e) {
    }
    //Now print out our name
    System.out.println("Hello World!"+whoami+""+delay);
    }
    }
    /** * Multimtest. A simple multithread thest program */
    public static void main(String[] args) {
    TestThread t1,t2,t3;
    //Create our test threads
    t1 = new TestThread("Thread1",(int)(Math.readom()*2000)); //實例化線程
    t2 = new TestThread("Thread2",(int)(Math.readom()*2000));
    t3 = new TestThread("Thread3",(int)(Math.readom()*2000));
    //Start each of the threads
    t1.start(); //啟動線程
    t2.start();
    t3.start();
    }
    }
    7.2.3 啟動一個線程
    程序啟動時總是調(diào)用main()函數(shù),因此main()是我們創(chuàng)建和啟動線程的地方:
    t1 = new TestThread("Thread1", (int)(Math.readom()*2000));
    這一行創(chuàng)建了一個新的線程。后面的兩個參數(shù)傳遞了線程的名稱和線程在打印信息前的延 時時間。因為我們直接控制線程,我們必須直接啟動它:
    t1.start();