建立線程

建立線程的方式有三種java

1.繼承Thread類ide

2.實現Runnable接口線程

3.實現Callable接口code

第三種方式,能夠經過FutureTask包裝類調用get()方法獲取到線程的返回值對象

也能夠經過ExecutorService建立的線程池調用submit()方法返回一個Future對象來獲取線程的返回值blog

public class FutureTest {

    public static void main(String[] args) {
        // futureTask();
        FutureTask<?> futureTask = new FutureTask<>(new CallableThreadTest());
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName() + " 的循環變量i的值" + i);
            if (i == 10) {
                new Thread(futureTask, "有返回值的線程").start();
            }
        }
        try {
            System.out.println("子線程的返回值:" + futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static class CallableThreadTest implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            int i = 0;
            for (; i < 20; i++) {
                System.out.println(Thread.currentThread().getName() + "--" + i);
            }
            return i;
        }
    }

    private static void futureTask() {
        FutureTask<Integer> task = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + "   " + "開始執行任務!");
            return 0;
        });
        new Thread(task, "新線程").start();
        try {
            System.out.print(task.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
相關文章
相關標籤/搜索