(一)線程管理_1---建立和運行線程

建立和運行線程

在Java語言中,有兩種建立線程的方式:java

(1)繼承Thread,重寫run方法ide

(2)實現Runnable接口,並做爲參數傳遞給Thread對象this


動手實現

(1)繼承Thread的方式線程

public class Calculator extends Thread {
    private int number;

    public Calculator(int number) {
        this.number=number;
    }

    @Override
    public void run() {
        for (int i = 0; i < number; i++) {
            System.out.printf("%s: %d\n",Thread.currentThread().getName(),i*number);
        }
    }

    public static void main(String[] args) {
        Calculator calculator=new Calculator(5);
        calculator.start();
    }
}
(2)實現Runnable接口的方式

public class Calculator2 implements Runnable {
    private int number;

    public Calculator2(int number) {
        this.number = number;
    }

    @Override
    public void run() {
        for (int i = 0; i < number; i++) {
            System.out.printf("%s: %d\n", Thread.currentThread().getName(), i * number);
        }
    }

    public static void main(String[] args) {
        Calculator2 calculator2 = new Calculator2(5);
        Thread thread = new Thread(calculator2);
        thread.start();
    }
}


要點

調用System.exit(),全部未結束的線程也將終止,線程啓動是經過調用start()方法;code

相關文章
相關標籤/搜索