Tuesday, June 23, 2009

Multi threads

following code creates a single Runnable instance and three Thread instances. All three Thread instances get the same Runnable instance. All threads are given unique names.
Finally, all three threads are started by invoking strat();

Thread class(Runnable Instance)
---------------------------------

public class NameRunnable implements Runnable
{
public void run()
{
for( int i =1; i<4 ;i++ )
{
System.out.println( "Run by : "+Thread.currentThread().getName() );
}
}
}

main class
----------

public class ManyNames
{
public static void main( String[] args )
{
NameRunnable nr = new NameRunnable();
Thread one = new Thread(nr);
one.setName( "One");
Thread two = new Thread(nr);
two.setName( "two");
Thread three = new Thread(nr);
three.setName( "three");
one.start();
two.start();
three.start();

}
}


result
--------

Run by : One
Run by : One
Run by : One
Run by : three
Run by : three
Run by : three
Run by : two
Run by : two
Run by : two

or

Run by : three
Run by : two
Run by : three
Run by : One
Run by : three
Run by : two
Run by : One
Run by : two
Run by : One

we can't decide the output. Schedular decides the threads execution time and order and it is out of JVM control , more from OS


when call start, it makes new call stack

No comments:

Post a Comment