TimerAndCallable的使用(暂不深入)

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值