Created
December 2, 2019 21:05
-
-
Save AnujJha-stack/def1ede2dfed1ea81d598cf1725c2d63 to your computer and use it in GitHub Desktop.
Java Threading Race Turtle &rabbit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.lang.Thread.sleep; | |
class Player implements Runnable{ | |
private int speed; | |
private String name; | |
private static int coveredDistance=0; | |
Player(String name, int speed){ | |
this.name = name; | |
this.speed = speed; | |
} | |
public void run(){ | |
System.out.println("I am "+name+"with speed"+speed); | |
while(coveredDistance < 1000){ | |
if(name.equals("rabbit")){ | |
coveredDistance += speed; | |
if(coveredDistance >= 1000){ | |
System.out.println(name+" WINS"); | |
} | |
} | |
if(name.equals("turtle")){ | |
coveredDistance += speed; | |
if(coveredDistance >= 1000){ | |
System.out.println(name+" WINS"); | |
} | |
} | |
// rabbit sleeps at 900m | |
if(name.equals("rabbit") && coveredDistance >= 900){ | |
try{ | |
sleep(999); | |
} | |
catch (InterruptedException e){ | |
System.out.println("Exception : "+e); | |
} | |
finally{ | |
coveredDistance += speed; | |
} | |
} | |
} | |
} | |
} | |
public class race { | |
public static void main(String[] args){ | |
Thread t1 = new Thread(new Player("turtle",1)); | |
Thread t2 = new Thread(new Player("rabbit",10)); | |
t1.start(); | |
t2.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment