死磕 java線程系列之建立線程的8種方式

(手機橫屏看源碼更方便)java


問題

(1)建立線程有哪幾種方式?spring

(2)它們分別有什麼運用場景?編程

簡介

建立線程,是多線程編程中最基本的操做,彤哥總結了一下,大概有8種建立線程的方式,你知道嗎?springboot

繼承Thread類並重寫run()方法

public class CreatingThread01 extends Thread {

    @Override
    public void run() {
        System.out.println(getName() + " is running");
    }

    public static void main(String[] args) {
        new CreatingThread01().start();
        new CreatingThread01().start();
        new CreatingThread01().start();
        new CreatingThread01().start();
    }
}

繼承Thread類並重寫run()方法,這種方式的弊端是一個類只能繼承一個父類,若是這個類自己已經繼承了其它類,就不能使用這種方式了。多線程

實現Runnable接口

public class CreatingThread02 implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " is running");
    }

    public static void main(String[] args) {
        new Thread(new CreatingThread02()).start();
        new Thread(new CreatingThread02()).start();
        new Thread(new CreatingThread02()).start();
        new Thread(new CreatingThread02()).start();
    }
}

實現Runnable接口,這種方式的好處是一個類能夠實現多個接口,不影響其繼承體系。異步

匿名內部類

public class CreatingThread03 {
    public static void main(String[] args) {
        // Thread匿名類,重寫Thread的run()方法
        new Thread() {
            @Override
            public void run() {
                System.out.println(getName() + " is running");
            }
        }.start();

        // Runnable匿名類,實現其run()方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " is running");
            }
        }).start();
        
        // 同上,使用lambda表達式函數式編程
        new Thread(()->{
            System.out.println(Thread.currentThread().getName() + " is running");
        }).start();
    }
}

使用匿名類的方式,一是重寫Thread的run()方法,二是傳入Runnable的匿名類,三是使用lambda方式,如今通常使用第三種(java8+),簡單快捷。ide

實現Callabe接口

public class CreatingThread04 implements Callable<Long> {
    @Override
    public Long call() throws Exception {
        Thread.sleep(2000);
        System.out.println(Thread.currentThread().getId() + " is running");
        return Thread.currentThread().getId();
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Long> task = new FutureTask<>(new CreatingThread04());
        new Thread(task).start();
        System.out.println("等待完成任務");
        Long result = task.get();
        System.out.println("任務結果:" + result);
    }
}

實現Callabe接口,能夠獲取線程執行的結果,FutureTask實際上實現了Runnable接口。函數式編程

定時器(java.util.Timer)

public class CreatingThread05 {
    public static void main(String[] args) {
        Timer timer = new Timer();
        // 每隔1秒執行一次
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " is running");
            }
        }, 0 , 1000);
    }
}

使用定時器java.util.Timer能夠快速地實現定時任務,TimerTask實際上實現了Runnable接口。函數

線程池

public class CreatingThread06 {
    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 100; i++) {
            threadPool.execute(()-> System.out.println(Thread.currentThread().getName() + " is running"));
        }
    }
}

使用線程池的方式,能夠複用線程,節約系統資源。測試

並行計算(Java8+)

public class CreatingThread07 {

    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
        // 串行,打印結果爲12345
        list.stream().forEach(System.out::print);
        System.out.println();
        // 並行,打印結果隨機,好比35214
        list.parallelStream().forEach(System.out::print);
    }
}

使用並行計算的方式,能夠提升程序運行的效率,多線程並行執行。

Spring異步方法

首先,springboot啓動類加上@EnableAsync註解(@EnableAsync是spring支持的,這裏方便舉例使用springboot)。

@SpringBootApplication
@EnableAsync
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

其次,方法加上@Async註解。

@Service
public class CreatingThread08Service {

    @Async
    public void call() {
        System.out.println(Thread.currentThread().getName() + " is running");
    }
}

而後,測試用例直接跟使用通常的Service方法如出一轍。

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class CreatingThread08Test {

    @Autowired
    private CreatingThread08Service creatingThread08Service;

    @Test
    public void test() {
        creatingThread08Service.call();
        creatingThread08Service.call();
        creatingThread08Service.call();
        creatingThread08Service.call();
    }
}

運行結果以下:

task-3 is running
task-2 is running
task-1 is running
task-4 is running

能夠看到每次執行方法時使用的線程都不同。

使用Spring異步方法的方式,能夠說是至關地方便,適用於先後邏輯不相關聯的適合用異步調用的一些方法,好比發送短信的功能。

總結

(1)繼承Thread類並重寫run()方法;

(2)實現Runnable接口;

(3)匿名內部類;

(4)實現Callabe接口;

(5)定時器(java.util.Timer);

(6)線程池;

(7)並行計算(Java8+);

(8)Spring異步方法;

彩蛋

上面介紹了那麼多建立線程的方式,其實本質上就兩種,一種是繼承Thread類並重寫其run()方法,一種是實現Runnable接口的run()方法,那麼它們之間到底有什麼聯繫呢?

請看下面的例子,同時繼承Thread並實現Runnable接口,應該輸出什麼呢?

public class CreatingThread09 {

    public static void main(String[] args) {
        new Thread(()-> {
            System.out.println("Runnable: " + Thread.currentThread().getName());
        }) {
            @Override
            public void run() {
                System.out.println("Thread: " + getName());
            }
        }.start();
    }
}

說到這裏,咱們有必要看一下Thread類的源碼:

public class Thread implements Runnable {
    // Thread維護了一個Runnable的實例
    private Runnable target;
    
    public Thread() {
        init(null, null, "Thread-" + nextThreadNum(), 0);
    }
    
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }
    
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        // ...
        // 構造方法傳進來的Runnable會賦值給target
        this.target = target;
        // ...
    }
    
    @Override
    public void run() {
        // Thread默認的run()方法,若是target不爲空,會執行target的run()方法
        if (target != null) {
            target.run();
        }
    }
}

看到這裏是否是豁然開朗呢?既然上面的例子同時繼承Thread並實現了Runnable接口,根據源碼,實際上至關於重寫了Thread的run()方法,在Thread的run()方法時實際上跟target都沒有關係了。

因此,上面的例子輸出結果爲Thread: Thread-0,只輸出重寫Thread的run()方法中的內容。


歡迎關注個人公衆號「彤哥讀源碼」,查看更多源碼系列文章, 與彤哥一塊兒暢遊源碼的海洋。

qrcode

相關文章
相關標籤/搜索