如何給run()方法傳參數
阿新 • • 發佈:2019-04-07
not eas 方式 方法 runnable style ont clas light
實現的方式主要有三種
1、構造函數傳參
2、成員變量傳參
3、回調函數傳參
問題:如何實現處理線程的返回值?
1、主線程等待法(優點:實現起來簡單,缺點:需要等待的變量一多的話,代碼就變的非常臃腫。而且不能精準控制時間)
public class CycleWait implements Runnable{ private String value; public void run() { try { Thread.currentThread().sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } value = "we have data now"; } public static void main(String[] args) throws InterruptedException { CycleWait cw = new CycleWait(); Thread t = new Thread(cw); t.start(); // while (cw.value == null){ // Thread.currentThread().sleep(100); // } t.join(); System.out.println("value : " + cw.value); } }
2、使用Thread類的join()阻塞當前線程以等待子線程處理完畢(缺點:精準度不夠)
3、通過Callable接口實現:通過FutureTask Or 線程池獲取
public class MyCallable implements Callable<String> { @Override public String call() throws Exception{ String value="test"; System.out.println("Ready to work"); Thread.currentThread().sleep(5000); System.out.println("task done"); return value; } }
FutureTask 實現方式
public class FutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask<String> task = new FutureTask<String>(new MyCallable()); new Thread(task).start(); if(!task.isDone()){ System.out.println("task has not finished, please wait!"); } System.out.println("task return: " + task.get()); } }
線程池實現方式
public class ThreadPoolDemo { public static void main(String[] args) { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); Future<String> future = newCachedThreadPool.submit(new MyCallable()); if(!future.isDone()){ System.out.println("task has not finished, please wait!"); } try { System.out.println(future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { newCachedThreadPool.shutdown(); } } }
如何給run()方法傳參數