1. 程式人生 > >Java的三種多線程

Java的三種多線程

子線程 image current ble 方法 get() 線程 對象 中間

項目結構

技術分享

繼承Thread類

/*
 * Thread類實現了Runnable接口
 */

public class MyThread extends Thread {
    @Override
    public void run() {
        for(int i=0;i<50;i++){
            System.out.println("MyThread子線程 : "+Thread.currentThread().getName()+"~~~"+i);
        }
    }
}

實現Runnable接口

public class MyRunnable implements
Runnable { @Override public void run() { for(int i=0;i<50;i++){ System.out.println("MyRunnable子線程 : "+Thread.currentThread().getName()+"~~~"+i); } } }

實現Callable<T>接口

import java.util.concurrent.Callable;
/*
 * FutureTask<V>類實現了RunnableFuture<V>接口,
 * RunnableFuture<V>接口實現了Runnable接口、Future<V>接口。
 * FutureTask<V>對象的get方法:等待計算完成,然後獲取其結果。
 
*/ public class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for(int i=0;i<100;i++){ sum += i; System.out.println("MyCallable子線程中間結果 : "+sum); } return sum; } }

運行

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;


public class Test {

    public static void main(String[] args) throws Exception {
        System.out.println("主線程 : "+Thread.currentThread().getName());
        MyThread thread = new MyThread();
        MyRunnable runnable = new MyRunnable();
        Thread thread2 = new Thread(runnable);
        MyCallable callable = new MyCallable();
        FutureTask<Integer> task = new FutureTask<Integer>(callable);
        Thread thread3 = new Thread(task);
        thread.start();
        thread2.start();
        thread3.start();
        int sum = task.get();
        System.out.println("MyCallable子線程最終結果 : " + sum); // 這段代碼總是最後執行
    }

}

Java的三種多線程