(4) Threads

First of all note that the aim of these lessons are not to cover simple basics (like no guarantee threads would run in an order) but to give a deeper understanding on tricky points.



Have you ever used a thread in java? You can't say no :D You should've definitely used public static void main(String[] args) { which is a thread!Threads begins as an instance of java.lang.Thread whether run() method is in Thread subclass or a Runnable implemetation ,you anyway need a Thread object.
  • A thread in java always begins by invoking run() method.
  • When you say t.start() the JVM creates a new stack for the newly created thread to run. .You call start() on a Thread instance and not Runnable instance.
  • Thread states are as follows
  


  • sleep() current thread would go to sleep - guaranteed
  • yield() current thread would be sent to runnable state - not guaraneed
  • join() if it was called as t.join(),currently running thread would stop executing until t completes - guaranteed
  •  Q)

1. public class Threads2 implements {
2.
3. public void run() {
4. System.out.println(“run.”);
5. throw new RuntimeException(“Problem”);
6. }
7. public static void main(String[] args) {
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println(“End of method.”);
11. }
12. }
Which two can be results? (Choose two.)
A. java.lang.RuntimeException: Problem
B. run.
java.lang.RuntimeException: Problem
C. End of method.
java.lang.RuntimeException: Problem
D. End of method.
run.
java.lang.RuntimeException: Problem
E. run.
java.lang.RuntimeException: Problem
End of method.
- See more at: http://www.searchcrone.com/2011/09/scjp-certification-java-thread-with-explanation#sthash.DtBxyVYD.dpuf
1. public class Threads2 implements Runnable { 
2. 
3. public void run() {
4. System.out.println(“run.”);
5. throw new RuntimeException(“Problem”);
6. }
7. public static void main(String[] args) {
8. Thread t = new Thread(new Threads2());
9. t.start();
10. System.out.println(“End of method.”);
11. }
12. }

Which two can be results? (Choose two.)

A. java.lang.RuntimeException: Problem


B. run.
java.lang.RuntimeException: Problem

C. End of method.
java.lang.RuntimeException: Problem

D. End of method.

run.
java.lang.RuntimeException: Problem

E. run.

java.lang.RuntimeException: Problem
End of method.


Fine, (D) is a straightforward answer.main thread finish executing and then gives the chance to t thread.
Now most probably you would think the other answer is (B) .As soon as t.start() happen,t thread get a chance so "run" would be printed and then the runtime exception report and program gracefully terminates. No it is not :D it would terminate after the runtime exception,but it is not the program but the relevant thread,so the main thread would be still running and print "End of method" as well.
So the answer is: (D),(E)

  • Look at this,


  • What happens if the same thread is started twice?
Throws:IllegalThreadStateException.If a Thread needs to be run more than once, then one should make an new instance of the same Thread and call start on it.
  • Q)
Runnable r = new Runnable() {
  public void run() {
    System.out.print("Cat");
  }
};
Thread t = new Thread(r) {
  public void run() {
    super.run();
    System.out.print("Dog");
  }
};
t.start();
what is the output?
Most inner one gets the chance and so would go to run() in Thread.Since it has overridden runnable's run() ,when super.run() is called it would first go there as well.So the output is
"CatDog".

  • Another important fact you should know about thread is even though you can do,t.setPriority(number between 1-10).Thread scheduler DOES NOT guarantee the behaviour you expected.Most probably it would be,but not at all the cases.
       You should further know that main thread has priority 5.
  • What you should know regarding daemon thread?
  1. Daemon threads are low priority threads and an eg. is java garbage collector
  2. When all the non daemon threads are over,at any point the program may terminate
  3. t.setDaemon(true)  [making a thread daemon]
    t.start()
these two should come in this order or a compilation fails.

  • Q)
public class TestOne implements Runnable {
public static void main (String[] args) throws Exception {
Thread t = new Thread(new TestOne());
t.start();
System.out.print(“Started”);
t.join();
System.out.print(“Complete”);
}
public void run() {
for (int i = 0; i < 4; i++) {
System.out.print(i);
}
}
}

What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints “StartedComplete”.
D. The code executes and prints “StartedComplete0123”.
E. The code executes and prints “Started0123Complete”.

1. public class TestOne implements Runnable {
2. public static void main (String[] args) throws Exception {
3. t = new Thread(new TestOne());
4. t.start();
5. System.out.print(“Started”);
6. t.join();
7. System.out.print(“Complete”);
8. }
9. public void run() {
10. for (int i = 0; i < 4; i++) {
11. System.out.print(i);
12. }
13. }
14. }
What can be a result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The code executes and prints “StartedComplete”.
D. The code executes and prints “StartedComplete0123”.
E. The code executes and prints “Started0123Complete”.

- See more at: http://www.searchcrone.com/2011/09/scjp-certification-questions-with-answers-explanation-javaset-6#sthash.6DR5Sqtw.dpuf
 
At the moment t.start() two threads are running.But when we look at the answers,all of them begin with "Started" so we should assume that it's the main thread that has run next. 

(Note:Theoretically, "Started" could come anywhere in between 0, 1, 2, 3. However in reality, since t.start() is an "expensive" method, it takes some time to complete, during which the main thread generally gets the chance to execute its next instruction.) 

t.join is run by the main thread as the code here.What does it truly command to do? It says that,the main thread should go to sleep (wait) till t finishes execution.

So then,0-3 should be printed.And then the Completed.

You see that Complete can not come before 0-3 because t.join guarantees execution of t thread first.

So the answer is : E  

From our next lesson,let's talk about the synchronization of threads...
   


 

Next PostNewer Post Previous PostOlder Post Home

0 comments:

Post a Comment