線程入門——編碼的變體

示例一:函數

/**
 * Created by Administrator on 2017/9/4.
 */
public class SimpleThread extends Thread {
    private int countDown = 5;
    private static int threadCount = 0;

    public SimpleThread() {
        //store the thread name
        super(Integer.toString(++threadCount));
        start();
    }

    public String toString() {
        return "#" + getName() + "(" + countDown + "),";
    }

    public void run() {
        while (true) {
            System.out.print(this);
            if (--countDown == 0) {
                return;
            }
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new SimpleThread();
        }
    }
}

以前全部的代碼都是實現了Runnable接口,而後將Runnable對象交給Thread構造函數。this

在很是簡單的狀況下,能夠直接從Thread繼承這種可替換的方式。如上所示。對象

輸出結果:繼承

相關文章
相關標籤/搜索