-
线程的实现方式
-
线程池的使用
实现Callable接口主要是可以获取到返回值,futureTask.get() 获取返回的值
示例代码:
public class ThreadImplCallable<T> implements Callable<T> { /** * 线程名称 */ private String threadName; /** * 构造函数 * * @param threadName 线程名称 */ public ThreadImplCallable(String threadName) { this.threadName = threadName; } /** * 重写call方法 */ @Override public T call() throws Exception { System.out.println(threadName); return (T)threadName; } }
public class ThreadMain { public static void main(String[] args) throws ExecutionException, InterruptedException { Callable<String> threadImplCallable = new ThreadImplCallable<>("Thread1"); FutureTask<String> futureTask = new FutureTask<>(threadImplCallable); Thread thread = new Thread(futureTask); thread.start(); String rValue = futureTask.get(); System.out.println("Thread1 return value is " + rValue); threadImplCallable = new ThreadImplCallable<>("Thread2"); futureTask = new FutureTask<>(threadImplCallable); thread = new Thread(futureTask); thread.start(); rValue = futureTask.get(); System.out.println("Thread2 return value is " + rValue); System.out.println("end"); } }
结果:
Thread1
Thread1 return value is Thread1
Thread2
Thread2 return value is Thread2
end