java多线程基础入门(二)有返回值的多线程
前言
之前我们使用多线程要么是继承Thread类,要么是实现Runnable接口,然后重写一下run()方法即可。 但是只有的话如果有死锁、对共享资源的访问和随时监控线程状态就不行了,于是在Java5之后就有了Callable接口。
简单的实现有返回值的线程
代码如下: CallableFuture类
package com.test.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableFuture {
public static void main(String[] args) {
//创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(3) ;
//创建三个有返回值的任务
CallableTest callableTest1 = new CallableTest("我是线程1") ;
CallableTest callableTest2 = new CallableTest("我是线程2") ;
CallableTest callableTest3 = new CallableTest("我是线程3") ;
Future future1 = pool.submit(callableTest1) ;
Future future2 = pool.submit(callableTest2) ;
Future future3 = pool.submit(callableTest3) ;
try {
System.out.println(future1.get().toString());
System.out.println(future2.get().toString());
System.out.println(future3.get().toString());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}finally{
pool.shutdown();
}
}
}
CallableTest·类:
package com.test.thread;
import java.util.concurrent.Callable;
public class CallableTest implements Callable {
private String threadName ;
public CallableTest(String threadName) {
this.threadName = threadName;
}
@Override
public Object call() throws Exception {
return threadName+"返回的信息";
}
}
运行结果:
我是线程1返回的信息我是线程2返回的信息
我是线程3返回的信息
总结
以上就是一个简单的例子,需要了解更多详情可以去看那几个类的API。
前言 之前我们使用多线程要么是继承Thread类,要么是实现Runnable接口,然后重写一下run()方法即可。 但是只有的话如果有死锁、对共享资源的访问和随时监控线程状态就不行了,于是在Java5之后就有了Callable接口。 简单的实现有返回值的线程 代码如下: CallableFuture类 package com.test.thread; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class CallableFuture { public static void main(String[] args) { //创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(3) ; //创建三个有返回值的任务 CallableTest callableTest1 = new CallableTest("我是线程1") ; CallableTest callableTest2 = new CallableTest("我是线程2") ; CallableTest callableTest3 = new CallableTest("我是线程3") ; Future future1 = pool.submit(callableTest1) ; Future future2 = pool.submit(callableTest2) ; Future future3 = pool.submit(callableTest3) ; try { System.out.println(future1.get().toString()); System.out.println(future2.get().toString()); System.out.println(future3.get().toString()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); }finally{ pool.shutdown(); } } } CallableTest·类: package com.test.thread; import java.util.concurrent.Callable; public class CallableTest implements Callable { private String threadName ; public CallableTest(String threadName) { this.threadName = threadName; } @Override public Object call() throws Exception { return threadName+"返回的信息"; } } 运行结果:我是线程1返回的信息 我是线程2返回的信息 我是线程3返回的信息 总结 以上就是一个简单的例子,需要了解更多详情可以去看那几个类的API。