Java建立執行緒的方式
阿新 • • 發佈:2019-07-28
Java中建立執行緒有三種,分別為實現Runnable介面,繼承Thread類,實現Callable介面。
1.Thread
public class MyThread extends Thread { public MyThread() { this.setName("MyThread"); } public void run() { while(true){ System.out.println("當前執行的執行緒: "+this.getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String []args){ new MyThread().start(); } }
- 優點:在run方法內直接用this獲取當前執行緒,無需使用Thread.currentThread()
- 缺點:Java不支援多繼承,如果繼承Thread類,就不能繼承其它類。任務與執行緒沒有分離,對於多個執行緒執行一樣的任務時需要多份任務程式碼,而Runnable沒有這個限制。
2.Runnable介面
public class RunnableTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub while (true) { System.out.println("當前執行的執行緒: " + Thread.currentThread().getName()); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { RunnableTask task = new RunnableTask(); new Thread(task).start(); new Thread(task).start(); } }
以上兩種方式沒有返回值。
3.Callable介面
public class CallableTest { public static void main(String []args) throws Exception { Callable<Integer> call = new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("thread start.."); Thread.sleep(2000); return 1; } }; FutureTask<Integer> task = new FutureTask<>(call); Thread t = new Thread(task); t.start(); System.out.println("do other thing.."); System.out.println("拿到執行緒的執行結果 : " + task.get()); } }
控制檯輸出:
do other thing..
thread start..
拿到執行緒的執行結果 : 1
Callable和Runnable的區別:
- Callable定義的方法是call,而Runnable定義的方法是run。
- Callable的call方法可以有返回值,而Runnable的run方法不能有返回值。
- Callable的call方法可丟擲異常,而Runnable的run方法不能丟擲異常。