兩種方式:一種繼承Thread類實現;一種通過實現Callable接口。
第一種方法:
因為實現Thread類的run方法自身是沒有返回值的,所以不能直接獲得線程的執行結果,但是可以通過在run方法里把最后的結果傳遞給實例變量,然后通過getXX方法獲取該實例變量的值。繼承實現的代碼:
package com.dxz.thread; import java.util.Random; import java.util.concurrent.TimeUnit; class RunThread extends Thread { private String runLog = ""; private String name; public RunThread(String name) { this.name = name; } public void run() { try { int time = new Random().nextInt(10); System.out.println("sleep "+ time +" second."); TimeUnit.SECONDS.sleep(time); this.runLog = this.name + time; } catch (Exception e) { e.printStackTrace(); } } public String getRunLog() { return this.runLog; } } package com.dxz.thread; public class RunThreadTest { public static void main(String[] args) throws InterruptedException { RunThread runT = new RunThread("world"); runT.start(); runT.join(); System.out.println("result:="+runT.getRunLog()); } }
結果:
sleep 3 second.
result:=world3
結果2:
sleep 2 second.
result:=world2
第二種方法:
繼承Callable接口后需要實現call方法,而call方法默認是可以有返回值的,所以可以直接返回想返回的內容。接口的實現代碼:
package com.dxz.thread; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; class CallThread implements Callable<String> { private String runLog = ""; private String name; public CallThread(String name) { this.name = name; } @Override public String call() throws Exception { try { int time = new Random().nextInt(10); System.out.println("sleep " + time + " second."); TimeUnit.SECONDS.sleep(time); this.runLog = this.name + time; } catch (Exception e) { e.printStackTrace(); } return runLog; } }
調用類:
package com.dxz.thread; import java.util.ArrayList; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class CallThreadTest { public static void main(String[] args) throws ExecutionException { String result = ""; ExecutorService exs = Executors.newCachedThreadPool(); ArrayList<Future<String>> al = new ArrayList<Future<String>>(); al.add(exs.submit(new CallThread("hello"))); al.add(exs.submit(new CallThread("world"))); for (Future<String> fs : al) { try { result += fs.get() + ","; } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("result:="+result); } }
結果:
sleep 5 second. sleep 3 second. result:=hello3,world5,