I have three threads in my programming.According to the threading concept all the threads run asynchronously. So every thread is executed by the processor randomly. If I have just paused the execution of one thread by using thread.sleep() then other thread should work . Right?? And when the sleep time for the thread is over then it should again continue with its execution. But in my case when I am pausing one thread by using t2.sleep(10000) then all other threads are also getting paused. But they should have worked normally while the t2 thread is in wait.Can anyone tell me why is it so?
import java.util.*;
class square extends Thread
{
public int x;
public square(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Square of the number is " + x*x);
}
}
class cube extends Thread
{
public int x;
public cube(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Cube of the number is " + x*x*x);
}
}
class randgen extends Thread
{
public void run()
{
int num=0;
Random r = new Random();
try
{
for(int i=0;i<5;i++)
{
num = r.nextInt(100);
System.out.println("The number generated is " + num);
square t2 = new square(num);
t2.start();
t2.sleep(10000);
cube t3 = new cube(num);
t3.start();
}
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}
public class Main
{
public static void main(String args[])
{
randgen obj = new randgen();
obj.start();
}
}
OUTPUT
The number generated is 50
Square of the number is 2500
(After 10s) Cube of the number is 125000
The number generated is 36
Square of the number is 1296
(After 10s)
The number generated is 75
Cube of the number is 46656
Square of the number is 5625
(After 10s)
The number generated is 92
Cube of the number is 421875
Square of the number is 8464
(After 10s)
The number generated is 0
Cube of the number is 778688
Square of the number is 0 (After 10s)
Cube of the number is 0
Why am I getting the output after 10s ,instead by the concept of thread that thread which I am pausing should only pause for 10s and other thread should work synchronously.
Aucun commentaire:
Enregistrer un commentaire