-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRaceDemo.java
More file actions
52 lines (43 loc) · 1.23 KB
/
RaceDemo.java
File metadata and controls
52 lines (43 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.util.*;
import java.io.*;
public class RaceDemo {
public static void main(String[] args) {
Racer racer = new Racer();
Thread tortoiseThread = new Thread(racer, "Tortoise");
Thread hareThread = new Thread(racer, "Hare");
//Race to start. tell threads to start
tortoiseThread.start();
hareThread.start();
}
}
class Racer implements Runnable {
public static String winner;
public void race(){
for(int distance=1;distance<=100;distance++){
System.out.println("Distance Covered by "+Thread.currentThread().getName()+ "is:"+distance +"meters");
//Check if race is complete if some one has already won
boolean isRaceWon = this.isRaceWon(distance);
if(isRaceWon){
break;
}
}
}
private boolean isRaceWon(int totalDistanceCovered){
boolean isRaceWon = false;
if((Racer.winner==null )&&(totalDistanceCovered==100)){
String winnerName = Thread.currentThread().getName();
Racer.winner = winnerName; //setting the winner name
System.out.println("Winner is :"+Racer.winner);
isRaceWon = true;
}else if(Racer.winner==null){
isRaceWon = false;
}else if(Racer.winner!=null){
isRaceWon = true;
}
return isRaceWon;
}
@Override
public void run() {
this.race();
}
}