*自定义线程对象,实现Callable接口,重写call()方法
*步骤:
* -实现Callable接口,先要返回值类型
* -重写call()方法,需要抛出异常
* -创建目标对象
* -创建执行服务:ExecutorService ser = Executor.newFixedThreadPool(1);
* -提交执行:Future res = ser.submit(t1);
* -获取结果:boolean r1 = res.get();
* -关闭服务:ser.shutdownNow();
*/
public class MyCallable implements Callable {
@Override
public Boolean call() throws Exception {
//线程执行体
for (int i = 0; i < 10; i++) {
}
return true;
}
public static void main(String[] args) throws ExecutionException,
InterruptedException {
// main线程,主线程
//创建线程实现类对象
MyCallable thread = new MyCallable();
MyCallable thread2 = new MyCallable();
//创建执行服务,参数是线程池线程数量
ExecutorService ser = Executors.newFixedThreadPool(2);
//提交执行
Future res = ser.submit(thread);
Future res2 = ser.submit(thread2);
boolean r1 = res.get();
boolean r2 = res2.get();
//关闭服务
ser.shutdownNow();
}
}
领取专属 10元无门槛券
私享最新 技术干货