public class Testmatch { public static boolean isOver = false; public static void main(String args[]){ Tortoise tt = new Tortoise(); Rabbit rr =new Rabbit(); tt.start(); rr.start(); } public static synchronized boolean win(){ if(!isOver){ isOver=true; return true; }return false; } public class Tortoise extends Thread{ public int terminal = 1000; public int curDis = 800; public void run(){ while(curDis<terminal){ try{ curDis++; System.out.println("乌龟当前跑了:"+curDis+"米。"); Thread.sleep(20); }catch (Exception e){} } System.out.println("乌龟到达了终点!"); if(!Testmatch.win()){ System.out.println("乌龟赢麻了!"); } } }}public class Rabbit extends Thread{ public int terminal = 1000; public int curDis = 0; public void run(){ while(curDis<terminal){ try{ curDis+=5; System.out.println("兔子当前跑了:"+curDis+"米。"); Thread.sleep(20); }catch (Exception e){} } System.out.println("兔子到达了终点!"); if(!Testmatch.win()){ System.out.println("兔子赢麻了!"); } } }代码中的 isOver的作用是什么
时间: 2024-02-14 19:24:11 浏览: 23
isOver是一个共享变量,作用是标识比赛是否已经结束。在win()方法中,当比赛结束时,将isOver设置为true,表示比赛已经结束。在Tortoise和Rabbit线程中,都会通过调用Testmatch类的win()方法来判断比赛是否结束,如果比赛已经结束,则不再继续执行,并输出相应的结果。由于isOver是一个共享变量,因此需要使用synchronized关键字来保证方法的同步性,避免多个线程同时修改isOver的值,导致结果的不确定性。
相关问题
1.下面的程序定义了一个线程类,请填空把程序补充完整。 public class MyThread implements (1) { private int num = 0; private boolean stop = false; public static void main(String[] args
) {
MyThread thread = new MyThread();
thread.start();
}
public void run() {
while(!stop) {
num++;
System.out.println("Current number is: " + num);
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
public void stopRunning() {
stop = true;
}
}
Runnable
.下面的程序定义了一个线程类,请填空把程序补充完整。 public class MyThread implements (1) { private int num = 0; private boolean stop = false; public static void main(String[] args) { MyThread my = new MyThread(); Thread td = new Thread(my);
public class MyThread implements Runnable {
private int num = 0;
private boolean stop = false;
public void run() {
while(!stop) {
System.out.println("num = " + num);
num++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread my = new MyThread();
Thread td = new Thread(my);
td.start();
}
}