《Java併發編程心得》第一章:線程&& 線程池(1.1 如何創建線程?)

如何創建線程?

創建線程主要有兩種方式繼承Thread類、實現Runable接口兩種方式。
通過查看Thread類的構造方法可知

繼承Thread類

public class MyThread extends Thread {

    @Override
    public void run() {
        System.out.println("This's my thread implement. name = " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread a = new MyThread();
        Thread b = new MyThread();

        a.start();
        b.start();
    }
}

實現Runable接口

public class MyRunable implements Runnable {
    
    @Override
    public void run() {
        System.out.println("This's my Runable implement. name = " + Thread.currentThread().getName());
    }

    public static void main(String[] args) {
        Thread a = new Thread(new MyRunable());
        Thread b = new Thread(new MyRunable());

        a.start();
        b.start();
    }
}

使用lambda表達式簡化寫法

對此種寫法有疑問的同學可以取看看“函數式接口”的定義。

public class MyLambdaDemo {
    public static void main(String[] args) {
        // 方式A
        Runnable runnable = () -> System.out.println("lambda to create a new thread. A");
        Thread a = new Thread(runnable);

        // 方式B
        Thread b = new Thread(() -> System.out.println("lambda to create a new thread. B"));

        a.start();
        b.start();
        
        // out 
        // lambda to create a new thread. A
        // lambda to create a new thread. B
    }
}

run方法和start方法的差異

在上面我們創建一個Thread類的實例後,是調用start方法來啓動線程的,與此同時還有run方法也可啓動類。那麼二者的差別在哪裏呢?
先上結論:run方法啓動線程不會創建一個新的線程,只會在當前線程執行Thread類的run方法體,換而言之,run方法啓動會串行的執行,就失去了創建一個Thread類的意義;而start會新開啓一個線程

public class RunOrStart {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());

        Thread a = new Thread(() -> System.out.println(Thread.currentThread().getName()));

        a.start();

        Thread b = new Thread(() -> System.out.println(Thread.currentThread().getName()));
        b.run();

        // out
        // main
        // Thread-0
        // main
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章