java——多线程回调函数

原文:https://blog.csdn.net/qq_34996727/article/details/80416277

修改了原文中: Thread 的方法 stop(),改为用标志位来终止线程

package thread_rabbit_tortoise;

public abstract class Animal extends Thread {
	 volatile boolean stop = false;
	public int length = 30;// 比赛长度
	public abstract void runing();
 
	@Override
	public void run() {
		while (!stop&&length>0) {
			runing();
			  }
	}
 
	public void terminate() {
		        stop = true;
		     }
 
	// 在需要回调数据的地方(两个子类需要),声明一个接口
	public static interface Calltoback {
		public void win();
	}
 
	// 2.创建接口对象
	public Calltoback calltoback;
}


package thread_rabbit_tortoise;

public class Rabbit extends Animal {
	
	public Rabbit() {
		setName("兔子");
	}
 
	@Override
	public void runing() {
		//兔子速度
		int dis = 5;
		length -= dis;
 
		System.out.println("兔子跑了" + dis + "米,距离终点还有" + length + "米");
		if (length <= 0) {
			length = 0;
			System.out.println("兔子获得了胜利");
			// 给回调对象赋值,让乌龟不要再跑了
			if (calltoback != null) {
				calltoback.win();
			}
		}
 
		try {
			if ((2000 - length) % 20 == 0) {	// 每20米休息一次,休息时间是1秒
				sleep(1000);
			} else {				//没0.1秒跑5米
				sleep(100);
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
 
}



package thread_rabbit_tortoise;

public class Tortoise extends Animal {
	public Tortoise() {
		setName("乌龟");// Thread的方法,给线程赋值名字
	}
 
	// 重写running方法,编写乌龟的奔跑操作
	@Override
	public void runing() {
		// 乌龟速度
		int dis = 2;
		length -= dis;
		System.out.println("乌龟跑了" + dis + "米,距离终点还有" + length + "米");
		if (length <= 0) {
			length = 0;
			System.out.println("乌龟获得了胜利");
			// 让兔子不要在跑了
			if (calltoback != null) {
				calltoback.win();
			}
		}
		try {
			sleep(100);						//没0.1秒跑2米
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
 
}



package thread_rabbit_tortoise;

import thread_rabbit_tortoise.Animal.Calltoback;

public class LetOneStop implements Calltoback {
	// 动物对象
	Animal an;
 
	// 获取动物对象,可以传入兔子或乌龟的实例
	public LetOneStop(Animal an) {
		this.an = an;
	}
 
	// 让动物的线程停止
	@Override
	public void win() {
		// 线程停止
		an.terminate();
	}
}


package thread_rabbit_tortoise;

public class MainClass {

	public static void main(String[] args) {

		Tortoise tortoise = new Tortoise();
		Rabbit rabbit = new Rabbit();

		LetOneStop letOneStop1 = new LetOneStop(tortoise);
		rabbit.calltoback = letOneStop1;
		LetOneStop letOneStop2 = new LetOneStop(rabbit);
		tortoise.calltoback = letOneStop2;

		tortoise.start();
		rabbit.start();
	}
 
}

 

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值