原创

多线程的创建方式之实现Callable接口

与实现Runable接口相比,Callable功能更强大

1.与run()方法相比,call()方法可以有返回值

2.call()方法可以抛出异常

3.call()方法支持泛型的返回值

4.call()方法的返回值以及线程的调用需要借助于FutureTask类来实现

5.FutureTask的run方法是线程安全的,使用的是CAS机制

示例代码:

package com.debuggg.exer;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class NumThread implements Callable {

@Override
public Object call() throws Exception {
int sum = 0;
for (int i = 0; i < 100; i++) {
if(i % 2 == 0){
sum += i;
System.out.println(i);
}
}
return sum;
}
}

public class CallableTest {
public static void main(String[] args) {
NumThread numThread = new NumThread();

FutureTask futureTask = new FutureTask(numThread);

Thread thread = new Thread(futureTask);
thread.start();

try {
int num = (int)futureTask.get();
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

}
}


正文到此结束
本文目录