之前我们使用多线程要么是继承
Thread
类,要么是实现Runnable
接口,然后重写一下run()
方法即可。但是只有的话如果有死锁、对共享资源的访问和随时监控线程状态就不行了,于是在Java5之后就有了Callable接口。
简单实现带返回值的线程
代码如下:CallableFuture类
packagecom.test.thread; importjava.util.concurrent.ExecutionException; importjava.util.concurrent.ExecutorService; importjava.util.concurrent.Executors; importjava.util.concurrent.Future; publicclassCallableFuture { publicstaticvoidmain(String[] args) { //创建一个线程池ExecutorServicepool=Executors.newFixedThreadPool(3) ; //创建三个有返回值的任务CallableTestcallableTest1=newCallableTest("我是线程1") ; CallableTestcallableTest2=newCallableTest("我是线程2") ; CallableTestcallableTest3=newCallableTest("我是线程3") ; Futurefuture1=pool.submit(callableTest1) ; Futurefuture2=pool.submit(callableTest2) ; Futurefuture3=pool.submit(callableTest3) ; try { System.out.println(future1.get().toString()); System.out.println(future2.get().toString()); System.out.println(future3.get().toString()); } catch (InterruptedExceptione) { e.printStackTrace(); } catch (ExecutionExceptione) { e.printStackTrace(); }finally{ pool.shutdown(); } } }
代码如下:CallableTest类
packagecom.test.thread; importjava.util.concurrent.Callable; publicclassCallableTestimplementsCallable { privateStringthreadName ; publicCallableTest(StringthreadName) { this.threadName=threadName; } @OverridepublicObjectcall() throwsException { returnthreadName+"返回的信息"; } }
运行结果
我是线程1返回的信息
我是线程2返回的信息
我是线程3返回的信息