java多線程的實現方法,java多線程實現

來源:互聯網
上載者:User

java多線程的實現方法,java多線程實現

java虛擬機器允許應用程式並發地運行多個線程。在java語言中,多線程的實現一般有以下三種方法:

1)實現Runnable介面,並實現該介面的run()方法

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

2)繼承Thread類,重寫run方法

class MyThread extends Thread{ public void run() {   System.out.println("Thread body");  }}public class Test{ public static void main(String[] args) {   MyThread thread = new MyThread();  thread.start(); }}

3)實現Callable介面,重寫call()方法

Callable對象實際是屬於Executor架構中的功能類,Callable介面與Runnable介面類似,但是提供了比Runnable更強大的功能,主要表現在以下三點:

(1)Callable可以在任務結束後提供一個傳回值,Runnable無法提供這個功能。

(2)Callable中的call()方法可以拋出異常,而Runnable的run()方法不能拋出異常。

(3)運行Callable可以拿到一個Future對象,Future對象表示非同步計算的結果。它提供了檢查計算是否完成的方法。由於線程屬於非同步計算模型,所以無法從其他線程中得到方法的傳回值,在這種情況下,就可以使用Future來監視目標線程調用call()方法的情況,當調用Future的get()方法擷取結果時,當前線程就會阻塞,直到call()方法結束返回結果。

import java.util.concurrent.*;public class CallableAndFuture{ 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();   Future<String> future = threadPool.submit(new CallableTest);   try{      System.out.println("waiting thread to finish");      System.out.println(future.get());   }   catch(Exception e)    {      e.printStackTrace();     } }}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.