问:如何给run()方法传参?
- 构造函数传参
- 成员变量传参
- 回调函数传参
问:如何实现处理线程的返回值?
主线程等待法(实现简单,缺点是需要自己写等待逻辑,当等待变量多时代码臃肿,而且无法明确等待时间,无法精准控制。不推荐使用)
使用Thread类的join()阻塞当前线程以等待子线程处理完毕(实现简单,精准控制。不过粒度不够细,比如子线程10次循环,想要第5次的时候去执行另一个子线程的run方法无法实现)
通过Callable接口实现:通过FutureTask Or 线程池获取
package interview.thread;
import java.util.concurrent.Callable;
/**
- @Author: cctv
- @Date: 2019/5/17 10:59
*/ public class MyCallable implements Callable { @Override public Object call() throws Exception { String value = "我可以跟你耗一整天"; System.out.println("Ready to work"); Thread.sleep(3000); System.out.println("task done"); return value; } }
package interview.thread;
import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask;
/**
- FutureTask方法获取线程返回值
- @Author: cctv
- @Date: 2019/5/17 11:01
*/ public class FutureTaskDemo { public static void main(String[] args) throws ExecutionException, InterruptedException { FutureTask task = new FutureTask(new MyCallable()); new Thread(task).start(); if(!task.isDone()){ System.out.println("Task has not finished, please wait!"); } // get可以阻塞知道子线程返回 也可以加个超时参数 System.out.println("task return :"+task.get()); } }
package interview.thread;
import java.util.concurrent.*;
/**
- 线程池获取返回值
- @Author: cctv
- @Date: 2019/5/17 11:10
*/ public class ThreadPoolDemo { public static void main(String[] args) { ExecutorService threadPool = Executors.newCachedThreadPool(); Future
future = threadPool.submit(new MyCallable()); if(!future.isDone()){ System.out.println("Task has not finished, please wait!"); } try { System.out.println("task return :"+future.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } finally { threadPool.shutdown(); } } }
使用线程池可以并发操作。两种方法同样都输出: