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();
);
}