Page 1 of 1
About Question enthuware.scjp.v6.2.497 :
Posted: Sat Aug 02, 2014 6:16 am
by anilkumarv
Code: Select all
public class TestClass extends Thread{
String name = "";
public TestClass(String str){
name = str;
}
public void run(){
try{
Thread.sleep( (int) (Math.random()*5000) );
System.out.println(name);
}
catch(Exception e)
{
}
}
public static void main(String[] str) throws Exception{
Thread t1 = new TestClass("tom");
Thread t2 = new TestClass("dick");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("harry");
}
}
The main thread waits for t1 and t2 to complete the execution , so only the last print statement is guaranteed to print last. What changes in the code is required if I need to ensure that tom, dick and harry is printed sequentially.Can thread priorities help ?.
Re: About Question enthuware.scjp.v6.2.497 :
Posted: Sat Aug 02, 2014 9:23 am
by anilkumarv
Code: Select all
public class TestClass extends Thread{
String name = "";
public TestClass(String str){
name = str;
}
public void run(){
try{
Thread.sleep( (int) (Math.random()*5000) );
System.out.println(name);
}
catch(Exception e)
{
}
}
public static void main(String[] str) throws Exception{
Thread t1 = new TestClass("tom");
Thread t2 = new TestClass("dick");
t1.start();
t1.join();
t2.start();//Thread t2 won't start untill t1 is complete
t2.join();
System.out.println("harry");
}
}
So the above code snippet will always print
tom
dick
harry
Kindly confirm.
Re: About Question enthuware.scjp.v6.2.497 :
Posted: Sat Aug 02, 2014 10:56 am
by admin
anilkumarv wrote:So the above code snippet will always print
tom
dick
harry
Kindly confirm.
No, that is not correct. Please go through the explanation. It explains why.
Re: About Question enthuware.scjp.v6.2.497 :
Posted: Sat Aug 02, 2014 11:47 am
by anilkumarv
admin wrote:anilkumarv wrote:So the above code snippet will always print
tom
dick
harry
Kindly confirm.
No, that is not correct. Please go through the explanation. It explains why.
I have gone through the explanation given.
Original code:
Code: Select all
t1.start();
t2.start();
t1.join();
t2.join();
Modified code
Code: Select all
t1.start();
t1.join();//t1 will run to its completion and then invoke t2.
t2.start();
t2.join();
Kindly confirm if my understanding is correct.
Re: About Question enthuware.scjp.v6.2.497 :
Posted: Sat Aug 02, 2014 1:44 pm
by admin
Yes, that is correct.