Callable,Runnable使用Demo



final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
ExecutorService threadPool = Executors.newSingleThreadExecutor();
ExecutorService threadPool2 = Executors.newFixedThreadPool(2);


/**
* A task that returns a result and may throw an exception. Implementors
* define a single method with no arguments called call. The Callable
* interface is similar to java.lang.Runnable, in that both are designed
* for classes whose instances are potentially executed by another
* thread. A Runnable, however, does not return a result and cannot
* throw a checked exception. The Executors class contains utility
* methods to convert from other common forms to Callable classes.
* 该接口类似于Runnable
* 接口,需要实现call方法,但是是有返回值的Runnable,并且可能会抛出异常,这两种接口都是为了其他线程使用而设计的. 当然该
*/


for (int i = 0; i < 2; i++) {
if (i==0) {
testCallable(simpleDateFormat, threadPool2);

}else {
testRunnable(simpleDateFormat, threadPool2);
}

}



private static void testCallable(final SimpleDateFormat simpleDateFormat,
ExecutorService threadPool) {
try {

// 使用方法1.用线程池來提交任务,
// 使用方法2.直接调用call方法
threadPool.submit( 
new Callable<Void>() {


@Override
public Void call() throws Exception {
System.err.println(simpleDateFormat.format(new Date())
+ "------Callable test begain-----");
Thread.sleep(2000);
System.err.println(simpleDateFormat.format(new Date())
+ "------Callable test end-----");
return null;
}
}
// .call();
 );

} catch (Exception e1) {
e1.printStackTrace();
}
}


private static void testRunnable(final SimpleDateFormat simpleDateFormat,
ExecutorService threadPool) {

//可以Runnable的run方法,也可以采用线程池来进行execute,或者是submit
threadPool.execute(
new Runnable() {

@Override
public void run() {
System.err.println(simpleDateFormat.format(new Date())
+ "------Runnable test begain-----");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.err.println(simpleDateFormat.format(new Date())
+ "------Runnable test end-----");
}
}
// .run();
);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mtj66

看心情

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值