Reputation: 528
For the given program, can you explain because I didn't get what I expected:
package javaapplication14;
class Mythread implements Runnable{
String myname;
int myage;
public Mythread( String par_name, int par_age){
myname = par_name;
myage = par_age;
}
public void run(){
try{
for(int i=1; i<=myage; i++) {
System.out.println("Happy birthday "+myname);
Thread.sleep(2000);
}
}catch(Exception e){
System.out.println();
}
}
}
public class JavaApplication14 {
public static void main(String[] args) {
Mythread m = new Mythread("Mutinda ", 2);
Mythread p = new Mythread("Boniface", 2);
Thread k = new Thread(m);
Thread q = new Thread(p);
k.start();
q.start();
Thread t = new Thread(m);
try{
for( int i=1; i<=5; i++){
System.out.println("Main thread executing");
Thread.sleep(1000);
}
}catch(Exception e){
System.out.println("Thread interrupted");
}
}
}
And this was my output:
Main thread executing
Happy birthday Boniface
Happy birthday Mutinda
Main thread executing
Main thread executing
Happy birthday Boniface
Happy birthday Mutinda
Main thread executing
Main thread executing
I expected this:
Main thread executing
Happy birthday Mutinda
Happy birthday Boniface
Main thread executing
Main thread executing
Happy birthday Mutinda
Happy birthday Boniface
Main thread executing
Main thread executing
I need someone to explain to me the priorites set up for the two threads k
and q
such that the output of q
becomes the first one than k
, regardless of the sleep time.
My argument: since k.start()
was called before the q.start()
, is expect my output to start with k
, since I called it first and the two takes the same sleep time.
Upvotes: 0
Views: 642
Reputation: 1979
You cannot rely on priorities for the multi-threading sequence execution. Java Threading basic rule is that it will be JVM dependent and that there can be no surety about the execution sequence of each thread. Priorities can influence but not ensure the execution
Upvotes: 0
Reputation: 533500
When you start threads, its because you have independant tasks which have little or no inter-dependence. As such you shouldn't expect a particular order of execution between the two threads, in fact most multi-threaded bugs come from making such assumptions.
If you want things to happen in a particular order use a single thread. If you can assume there is no particular order for tasks, only then use multiple threads.
Upvotes: 3
Reputation: 732
Basically your argument is wrong. start() function does not start a tread. It simply puts it into runnable state.
Upvotes: 3