创建线程3--实现Callable接口
2019-07-07 23:44 更新
注意:
1.实现Runnable接口创建线程没有直接的返回值,但可以通过额外添加成员变量和get方法实现同样的效果。
2.如果run方法内有异常不能抛出,要在内部直接抓取。
1.实现Callable接口创建线程的简单实现:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程
ExecutorService executorService = Executors.newFixedThreadPool(1);
Race tortoise = new Race();
//获取值
Future<Integer> future = executorService.submit(tortoise);
int sum = future.get();
System.out.println(sum);
executorService.shutdown();
}
}
class Race implements Callable<Integer>{
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
return 1000;
}
}
2.实现Callable接口创建线程的复杂实现:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//创建线程
ExecutorService executorService = Executors.newFixedThreadPool(2);
Race tortoise = new Race("乌龟", 1000);
Race rabbit = new Race("兔子", 500);
//获取值
Future<Integer> tortoiseFuture = executorService.submit(tortoise);
Future<Integer> rabbitFuture = executorService.submit(rabbit);
Thread.sleep(2000);//2秒
tortoise.setFlag(false);//停止线程体循环
rabbit.setFlag(false);
int tortoiseSum = tortoiseFuture.get();
int rabbitSum = rabbitFuture.get();
System.out.println("乌龟跑了:" + tortoiseSum + "步。");
System.out.println("兔子跑了:" + rabbitSum + "步。");
executorService.shutdown();
}
}
class Race implements Callable<Integer>{
private String name;//名称
private long time;//延迟时间
private boolean flag = true;//是否继续走
private int step;//步
public Race(String name, long time) {
this.name = name;
this.time = time;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
while(flag) {
Thread.sleep(time);//延迟
step++;
}
return step;
}
}
以上内容是否对您有帮助:
更多建议: