多线程——龟兔赛跑Runnable接口
程序员文章站
2022-05-02 10:09:12
...
package thread;
public class competition implements Runnable{
private static String contest;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("Rabbit ")){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (Thread.currentThread().getName().equals("Tortoise ")){
try {
Thread.sleep(95);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean end = endGame(i);
if (end){
break;
}
System.out.println(Thread.currentThread().getName()+" ran "+i+" steps.");
}
}
private boolean endGame(int steps){
if (contest!=null){
return true;
}
if (steps>=100){
contest = Thread.currentThread().getName();
System.out.println("contest is "+contest);
return true;
}
return false;
}
public static void main(String[] args) {
competition competition = new competition();
new Thread(competition,"Rabbit ").start();
new Thread(competition,"Tortoise ").start();
}
}
上一篇: 心灵鸡汤“我做错了什么”?
下一篇: Android 通过JNI实现守护进程