首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

多线程实现3-1:Callable接口

*自定义线程对象,实现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();

}

}

  • 发表于:
  • 原文链接https://page.om.qq.com/page/OPot-K3oE0Oaj7nSPpI-u_Rw0
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券
http://www.vxiaotou.com