龟兔赛跑--多线程运行 *** 作判断,继承Runnable接口
可自己设置总路程和角色
代码如下:
public class Test03 implements Runnable { private static String winner; @Override public void run() { //比赛总里程100步 for (int i = 0; i <=100; i++) { //调用getWinner方法判断步数是否满足总里程100,有Winner返回ture,否则false boolean flag = getWinner(i); //有Winner则为false,不满足条件,跳过if判断 if (flag){ //为ture则进入条件,break结束循环 break; } System.out.println(Thread.currentThread().getName()+"跑了"+i+"步"); } } public boolean getWinner(int steps){ if (winner!=null){//有赢家 return true; }else { if (steps>=100){ winner = Thread.currentThread().getName(); System.out.println("赢家是"+winner); return true; } } return false; } public static void main(String[] args) { //一个主线程,两个分线程分别去抢占主程序的cpu资源 Test03 test03 = new Test03(); new Thread(test03,"乌龟").start(); new Thread(test03,"兔子").start(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)