1. 程式人生 > >線程池(6)簡單創建線程3種實現

線程池(6)簡單創建線程3種實現

all () exceptio trace png mbo alt for ava

3種實現:thread、runnable、callable

技術分享圖片

1、thread

@Slf4j
public class MyThread extends Thread {
    @Override
    public void run() {
        log.info("線程ID:{}",Thread.currentThread().getId());
    }
    
}

public class MyTest {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
輸出:10:09:08.152 [Thread-0] INFO c.e.thread.MyThread:9 - 線程ID:10

2、runnable

@Slf4j
public class MyRunnable implements Runnable {
    public MyRunnable() {
    }
    @Override
    public void run() {
        log.info("線程ID:{}",Thread.currentThread().getId());
    }
}

public class MyTest {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        
new Thread(r).start(); } }
輸出:10:09:20.272 [Thread-0] INFO c.e.r.MyRunnable:10 - 線程ID:10

3、callable

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 10000*100; i++) {
            sum 
= sum +1; } return sum; } } import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; import lombok.extern.slf4j.Slf4j; @Slf4j public class MyTest { public static void main(String[] args) { MyCallable c = new MyCallable(); FutureTask<Integer> result = new FutureTask<>(c); new Thread(result).start(); try { Integer sum = result.get(); log.info("{}",sum); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
輸出:10:08:49.349 [main] INFO c.e.callable.MyTest:15 - 1000000

線程池(6)簡單創建線程3種實現