How multitasking or multi-threading is working in Java
It's a totally random process, we cannot predict the order.
Screenshot/Output:
| Using the try block (sleep method) |
| Without using the try block (sleep method) |
The Code:
class Demo1 extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println("Thread 1 "+i);
/*try
{
Thread.sleep(200);
}
catch(InterruptedException e)
{
System.out.println(e);
}*/
}
}
}
class Demo2 extends Thread
{
synchronized public void run()
{
for(int i=0;i<20;i++)
{
System.out.println("\t.\t Thread 2 "+i);
/*try
{
Thread.sleep(100);
}
catch(InterruptedException e)
{
System.out.println(e);
}*/
}
}
}
class Demo3 extends Thread
{
public void run()
{
for(int i=0;i<30;i++)
{
System.out.println("\t.\t.\t.\t Thread 3 "+i);
/*try
{
Thread.sleep(300);
}
catch(InterruptedException e)
{
System.out.println(e);
}*/
}
}
}
public class myclass
{
public static void main(String arg[])
{
Demo1 d1 = new Demo1();
d1.start();
Demo2 d2 = new Demo2();
d2.start();
Demo3 d3 = new Demo3();
d3.start();
for(int i=0;i<50;i++)
{
System.out.println("\t.\t.\t.\t.\t.\t MainThread "+i);
/*try
{
Thread.sleep(400);
}
catch(InterruptedException e)
{
System.out.println(e);
}*/
}
}
}
/*Remove the comment tags and include the code and see what happens..*/
/*Its totally random output without synchonization.. run 2 3 time and see the different combinations*/
Comments
Post a Comment