Professional Documents
Culture Documents
Thead Question
Thead Question
Q1.
How many way to define and instantiate a thread ? And which one is better
way and why ?
Ans:-
Extending the thread class is easiest way but it is not good approach,
because when you extending the java.lang.Thread class in your class,
you can’t extend any other class in your class in future. So object-
oriented perspective, suggesting for implementing Runnable interface.
Q2.
Ans:-
Any action that you want to execute in a separate thread as the job to
do in run() method.
Every thread in java executes in new call stack. When run() method is
called then a new stack is created and all things that are in run()
method will execute in new call stack.
}
Q3.
What will be the output of the following code? It will gives compile time error
or run time ?
package org.com.core.thread;
Ans :-
The above code will execute successfully. Because if you extends the
thread and you have not override run() method then Thread will
execute its own run method.
Q4.
Ans:-
package org.com.core.thread;
The overloaded run(int n) method not see by the Thread class. Thead
class will expect only run() method with no arguments. And when it
will find the run() method with no argument, thread will executed in
separate call stack after the thread has been started. The method
run(int n) is just like a other normal method.
Q5.
package org.com.core.thread;
Ans.
Output :-
TestThread
Q6.
Ans.
Q7.
package org.com.core.thread;
Ans.
Output:-
Same as for –
t.run();
or
r.run();
Q8.
Ans.
package org.com.core.thread;
Output:
Q9.
Ans.
Example-
package org.com.core.thread;
The above code will execute from main that is itself a thread so it will
run in separate stack.
While thFun() executing it will reach t.start(); this line then it will
starts new thread and now it will create a new stack like as
Q10.
Ans.
NO, once a thread has been started, it can never be start again. Still
you do this; it will give RuntimeException name as
IllegalThreadStateException. In any case, either thread’s run() method
has completed or not, means a runnable thread or dead thread cannot
be restarted.
Example –
package org.com.core.thread;
Q11.
Ans.
Q12.
Ans.
Ans.
New
Runnable
Running
Waiting/blocked/sleep
Q14.
Ans.
Thread.NORM_PRIORITY(5)
Thread.MAX_PRIORITY(10)
t.setPriority(5);
t.start();
Q15.
Ans.
yield() method is static method of Thread class. The job of the method
is to make a chance for other thread that are having same priority in
Runnable pool. And running thread will go back in Runnable pool.
Q16.
Ans.
For this, Thread B will join Thread A, After that Thread B will not be in
runnable until Thread A has finishd.