package knowledgepoint;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
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;
//Callaable可以抛出异常及得到返回值
public class CallableAndTimer {
//使用Timer(了解)
public static void main1(String[] args) {
Timer timer = new Timer("定时器");
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("TimerTask是Runnable的子类");
}
}, new Date(System.currentTimeMillis()+1000),1000);
}
public static void main2(String[] args) throws InterruptedException, ExecutionException {
//创建线程 //创建线程的个数
ExecutorService executorservice = Executors.newFixedThreadPool(1);
//获取值
Future<Integer> restult = executorservice.submit(new Race1());
int num = restult.get();
System.out.println(num);
//停止服务
executorservice.shutdown();
}
//使用Callable接口模拟龟兔赛跑
public static void main(String[] args) throws InterruptedException, ExecutionException {
//开启两个线程
ExecutorService executorService = Executors.newFixedThreadPool(2);
Race r1= new Race(1000);
Future<Integer> restult1 =executorService.submit(r1);
Race r2= new Race(500);
Future<Integer> restult2 = executorService.submit(r2);
Thread.sleep(5000);
/*r1.setFlag(false);
r2.setFlag(false);*/
r1.flag = false;
r2.flag = false;
int value1= restult1.get();
System.out.println("乌龟跑了"+value1+"步");
int value2= restult2.get();
System.out.println("兔子跑了"+value2+"步");
executorService.shutdown();
}
}
class Race implements Callable<Integer>{
int step;
boolean flag= true;
String name;
long time;
public Race(long time) {
this.time = time;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public Integer call() throws Exception {
System.out.println("启动");
while(flag) {
Thread.sleep(time);
step++;
}
return step;
}
}
//确定线程执行完毕的返回值类型
class Race1 implements Callable<Integer>{
@Override//与此处相对应
public Integer call() throws Exception {
return 1000;
}
}