I want to use Thread.sleep() in my java application. But does not work. Program works after removing sleep.
In my program I am running multiple threads and want that each move forward at a variable speed. Some may get executed more some less. So I am using sleep in each with a random number as argument. If there another way to do this. Without using sleep.
Here is the part where I am using the sleep function.
public void run()
{
Random r = new Random();
int t;
while(true)
{
if(total == 1)
{
// win();
break;
}
if(doa == 1)
break;
// Player x = e[r.nextInt(20)%2];
Player x = choose();
x.attack(this, 10 + (power==1?5:0));
if(r.nextInt(100)%(5 - (power==2?2:0)) == 0)
System.out.println(" " + name + " used Potion effect (" + potionno++ + ") .. now " + name + "'s Health is " + (h+= 10 + r.nextInt(20)));
try
{
sleep(50 + r.nextInt(1000));
}
catch(InterruptedException c)
{ ; }
}
if(doa == 1)) {
// and so on
.
.
and here is my doGet function used for initiation
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s;
s = request.getParameter("name");
try{
Player.out = out;
Player.e[0] = new Player("Kartik",2);
Player.e[1] = new Player(s,1);
Player.e[2] = new Player("Anirudh",3);
Player.e[3] = new Player("Vinita");
Player.e[4] = new Player("Shivank");
for(Player p: Player. e)
p.start();
}
catch(Exception e)
{
out.print("WRONG");
}
}