日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

java中实现多线程的方法有哪几种

發(fā)布時(shí)間:2024/3/26 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java中实现多线程的方法有哪几种 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

實(shí)現(xiàn)多線程的方法有三種:

  • 實(shí)現(xiàn)Runnable接口,并實(shí)現(xiàn)接口的run()方法
  • 繼承Thread類,重寫run方法
  • 實(shí)現(xiàn)Callable接口,重寫call()方法
  • 實(shí)現(xiàn)Runnable接口,并實(shí)現(xiàn)接口的run()方法

    (1)自定義類并實(shí)現(xiàn)Runnable接口,實(shí)現(xiàn)run()方法。
    (2)創(chuàng)建Thread對(duì)象,用實(shí)現(xiàn)Runnable接口的對(duì)象作為參數(shù)實(shí)例化該Thread對(duì)象。
    (3)調(diào)用Thread的start()方法

    class MyThread implements Runnable {public void run(){System.out.println("線程運(yùn)行");} } public class Test{public static void main(String[] args){MyThread thread=new MyThread();Thread t=new Thread(thread);t.start();//開啟線程} }

    繼承Thread類,重寫run方法

    當(dāng)執(zhí)行start()方法后,并不是立即執(zhí)行多線程代碼,而是使得該線程變?yōu)榭蛇\(yùn)行態(tài),什么運(yùn)行多線程代碼由操作系統(tǒng)決定。

    class MyThread extends Thread{public void run(){System.out.println("線程運(yùn)行");} } public class Test{public static void main(String[] args){MyThread thread=new MyThread();thread.start();//開啟線程} }

    實(shí)現(xiàn)Callable接口,重寫call()方法

    Callable對(duì)象屬于Executor框架中的功能類,Callable與Runnable接口類似,但是提供了比Runnable更強(qiáng)大的功能:

  • Callable可以在任務(wù)結(jié)束后提供一個(gè)返回值,Runnable無(wú)法提供這個(gè)功能。
  • Callable中的call()方法可以拋出異常,而Runnable的run()方法不能拋出異常。
  • 運(yùn)行Callable可以拿到一個(gè)Future對(duì)象,Future對(duì)象表示異步計(jì)算的結(jié)果。可以使用Future來(lái)監(jiān)視目標(biāo)線程調(diào)用call()方法的使用情況,當(dāng)調(diào)用Future的get()方法以獲取結(jié)果是,當(dāng)前線程就會(huì)阻塞,直到call()方法結(jié)束返回結(jié)果為止。
  • import java.util.concurrent.*; public class CallableAndFuture{//創(chuàng)建線程public static class CallableTest implements Callable<String>{public String call() throws Exception{return "Hello World";}}public static void main(String[] args){ExecutorService threadPool=Executors.newSingleThreadExecutor();//啟動(dòng)線程Future<String> future=threadPool.submit(new CallableTest());try{System.out.println("等待線程執(zhí)行完成");System.out.println(future.get());//等待線程結(jié)束,并獲取返回結(jié)果}catch(Exception e){e.printStackTrace();}} }

    輸出結(jié)果為:

    等待線程執(zhí)行完成 Hello World!

    以上三種方式中,前兩種方式線程執(zhí)行完之后沒(méi)有返回值,第三種有。一般推薦實(shí)現(xiàn)Runnable接口的方式,原因如下:Thread類定義了多種方法可以被派生類使用或重寫,但是只有run方法是必須被重寫的,在run方法中實(shí)現(xiàn)這個(gè)線程的主要功能。所以沒(méi)有必要繼承Thread,去修改其他方法。

    總結(jié)

    以上是生活随笔為你收集整理的java中实现多线程的方法有哪几种的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

    如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。