Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817
Moderator: admin
anilkumarv
Posts: 3 Joined: Sat Aug 02, 2014 3:04 am
Contact:
Post
by anilkumarv » Sat Aug 02, 2014 6:16 am
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 ?.
anilkumarv
Posts: 3 Joined: Sat Aug 02, 2014 3:04 am
Contact:
Post
by anilkumarv » Sat Aug 02, 2014 9:23 am
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.
admin
Site Admin
Posts: 10065 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Sat Aug 02, 2014 10:56 am
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.
If you like our products and services, please help us by posting your
review here .
anilkumarv
Posts: 3 Joined: Sat Aug 02, 2014 3:04 am
Contact:
Post
by anilkumarv » Sat Aug 02, 2014 11:47 am
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.
admin
Site Admin
Posts: 10065 Joined: Fri Sep 10, 2010 9:26 pm
Contact:
Post
by admin » Sat Aug 02, 2014 1:44 pm
Yes, that is correct.
If you like our products and services, please help us by posting your
review here .
Users browsing this forum: Bing [Bot] and 95 guests