Java 實(shí)現(xiàn)多線程的三種方式

轉(zhuǎn)載自

http://www.itdecent.cn/p/19f9ce1d82a4

繼承 Thread 類

run() 方法 VS start() 方法:

  • run() 方法:普通的成員方法
  • start() 方法:負(fù)責(zé)啟動(dòng)一個(gè)新的線程,并調(diào)用 run() 方法
  • 因此啟動(dòng)線程,需要使用 start() 方法
public class MultiThread_Test {
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }
}

class MyThread extends Thread {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

實(shí)現(xiàn) Runnable 接口

實(shí)際上 Thread 類也是實(shí)現(xiàn)了 Runnable 接口:
class Thread implements Runnable {}

啟動(dòng) Runnable 實(shí)例時(shí),需要放在 Thread 中,然后調(diào)用 start() 方法

public class MultiThread_Test {
    public static void main(String[] args) {
        MyRunnable mr = new MyRunnable();
        new Thread(mr).start();
    }
}

class MyRunnable implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

實(shí)現(xiàn) Callable 接口

  • Java 5 開(kāi)始提供
  • 可以返回結(jié)果(通過(guò) Future),也可以拋出異常
  • 需要實(shí)現(xiàn)的是 call() 方法
  • 以上兩點(diǎn)也是 Callable 接口 與 Runnable 接口的區(qū)別
public class MultiThread_Test {
    public static void main(String[] args) throws Exception {
        ExecutorService es = Executors.newSingleThreadExecutor();

        // 自動(dòng)在一個(gè)新的線程上啟動(dòng) MyCallable,執(zhí)行 call 方法
        Future<Integer> f = es.submit(new MyCallable());

        // 當(dāng)前 main 線程阻塞,直至 future 得到值
        System.out.println(f.get());

        es.shutdown();
    }
}

class MyCallable implements Callable<Integer> {
    public Integer call() {
        System.out.println(Thread.currentThread().getName());

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return 123;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容