-
线程的实现方式
-
java 多线程之 extends Thread
-
java 多线程之 implements Runnable
-
java 多线程之 implements Callable
-
-
线程池的使用
-
线程池简介
-
ThreadPoolExecutor
-
java 线程池之 newScheduledThreadPool
-
java 线程池之 newCachedThreadPool
-
java 线程池之 newFixedThreadPool
-
java 线程池之 newSingleThreadExecutor
-
-
ForkJoinPool
-
java 线程池之 newWorkStealingPool
-
-
Complet ableFuture
-
CompletableFuture 的使用示例
-
-
实现Callable接口主要是可以获取到返回值,futureTask.get() 获取返回的值
示例代码:
public class ThreadImplCallable<T> implements Callable<T> {/*** 线程名称*/private String threadName;/*** 构造函数** @param threadName 线程名称*/public ThreadImplCallable(String threadName) {this.threadName = threadName;}/*** 重写call方法*/@Overridepublic 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