App下載

Java實(shí)現(xiàn)多線程的三種方式 總結(jié)三種方式的對(duì)比

陽光溫暖空屋 2021-08-10 11:41:22 瀏覽數(shù) (2889)
反饋

本文將為大家簡單地介紹一下Java中的多線程的作用,以及在Java中實(shí)現(xiàn)多線程的三種方法使用的實(shí)例代碼,和三種方式的對(duì)比總結(jié)內(nèi)容,供大家學(xué)習(xí)參考!

介紹

多線程主要的作用就是充分利用cpu的資源。單線程處理,在文件的加載的過程中,處理器就會(huì)一直處于空閑,但也被加入到總執(zhí)行時(shí)間之內(nèi),串行執(zhí)行切分總時(shí)間,等于每切分一個(gè)時(shí)間*切分后字符串的個(gè)數(shù),執(zhí)行程序,估計(jì)等幾分鐘能處理完就不錯(cuò)了。而多線程處理,文件加載與差分過程中

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

1.繼承Thread

通過Thread繼承,并重寫run方法來實(shí)現(xiàn)多線程,案例如下:

public class ThreadPattern extends Thread {
    @Override
    public void run() {
        System.out.println("繼承Thread當(dāng)前執(zhí)行線程"+Thread.currentThread().getName());
    }
}
// 測試
public void threadTest() throws ExecutionException, InterruptedException {
        ThreadPattern pattern = new ThreadPattern();
        pattern.start();
    }

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

Runable的實(shí)現(xiàn)類作為Thread的構(gòu)造參數(shù),來實(shí)現(xiàn)多線程,案例如下:

public class RunnablePattern implements Runnable{
    @Override
    public void run() {
        System.out.println("實(shí)現(xiàn)Runnable方式,當(dāng)前執(zhí)行線程"+Thread.currentThread().getName());
    }
}
// 測試
public void runnableTest() throws ExecutionException, InterruptedException {
        RunnablePattern runnablePattern = new RunnablePattern();
        Thread thread = new Thread(runnablePattern);
        thread.start();
    }

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

實(shí)現(xiàn)Callable接口重寫call()方法,然后包裝成FutureTask,然后再包裝成Thread,其實(shí)本質(zhì)都是實(shí)現(xiàn)Runnable 接口。案例如下:

public class CallablePattern  implements Callable {
    @Override
    public Object call() throws Exception {
        System.out.println("實(shí)現(xiàn)Callable方式,當(dāng)前執(zhí)行線程"+Thread.currentThread().getName());
        return "1";
    }
}
// 測試
public void callableTest() throws ExecutionException, InterruptedException {
        CallablePattern callablePattern = new CallablePattern();
        FutureTask<String> futureTask = new FutureTask<>(callablePattern);
        new Thread(futureTask).start();
    }

二、總結(jié)對(duì)三種使用方式的對(duì)比

1、Thread:繼承的方式,由于java的單一繼承機(jī)制。就無法繼承其他類,使用起來就不夠靈活。

2、Runnable:實(shí)現(xiàn)接口,比Thread類更加的靈活,沒有單一繼承的限制。

3、Callable:Thread和runnable都重寫run方法并且沒有返回值,Callable是重寫call()方法并且有返回值,借助FutureTask類來判斷線程是否執(zhí)行完畢或者取消線程執(zhí)行, 一般情況下不直接把線程體的代碼放在Thread類中,一般通過Thread類來啟動(dòng)線程。

4:Thread類實(shí)現(xiàn)Runnable ,Callable封裝成FutureTask,FutureTask實(shí)現(xiàn)RunnableFuture,RunnableFuture實(shí)現(xiàn)Runnable,所以Callable也算是一種Runnable,所以實(shí)現(xiàn)的方式本質(zhì)都是Runnable實(shí)現(xiàn)。

以上就是關(guān)于Java中實(shí)現(xiàn)多線程的三個(gè)方式的使用和對(duì)比總結(jié)的詳細(xì)內(nèi)容,想要了解更多相關(guān)Java多線程的內(nèi)容,請搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章!


1 人點(diǎn)贊