From what i read here Thread join on itself ;
When join method is called on itself, it should wait forever
I am currently preparing for ocajp 8 certification,for which going through dumps and when i got this question ,what i thought is main should wait forever
public class startinginconstructor extends Thread
{
private int x=2;
startinginconstructor()
{
start();
}
public static void main(String[] args) throws Exception
{
new startinginconstructor().makeitso();
}
public void makeitso() throws Exception
{
x=x-1;
System.out.println(Thread.currentThread().getName()+" about to call join ");
join();
System.out.println(Thread.currentThread().getName()+" makeitso completed ");
// above line shouldn't be executed (method shouldn't be completed as well )since it joined on itself..?
}
public void run()
{
System.out.println(Thread.currentThread().getName()+" run started ");
x*=2;
System.out.println(Thread.currentThread().getName()+" run about to complete ");
}
}
program ended with following output
main about to call join
Thread-0 run started
Thread-0 run about to complete
main makeitso completed
Did i wrongly get the meaning of thread waiting forever or is there something i am missing
note: I know starting thread from constructor is not a recommended practice.. this is exact question in the dumps so i just pasted it (* not pretty much exact actually,i have placed println statements to see flow of the program)
There is no thread that joins itself in your example.
The main() thread in your example creates a new thread and then it joins the new thread.
Don't confuse Thread (i.e., the java object) with thread (the execution of the code.) All of your methods belong to the same Thread object, but they run in two different threads.
James is correct (+1 from me), I'm just trying to make this more explicit. Here is what happens:
Your main thread constructs the startinginconstructor constructor.
The constructor calls start, which will result in the startinginconstructor object having its run method in the new thread.
After that the main thread will proceed to call makeitso. In makeitso this is the startinginconstructor object, so the result is that the main thread waits until the thread represented by the startinginconstructor object has finished.
Java objects can be called by any thread, just because an object extends Thread doesn't mean any invocation of that method is happening on that thread.
Related
I was trying to use java.lang.Object.wait() method and have written 3 different sample codes wherein I am getting different behavior of wait() method.
sample 1)
class Main {
public static void main(String[] args) throws InterruptedException {
ThreadB b = new ThreadB();
b.start();
Thread.sleep(10000);
synchronized (b) {
System.out.println("main thread trying to call wait() method"); //--> 3
b.wait();
System.out.println("main thread got notification");
System.out.println(b.total);
}
}
}
class ThreadB extends Thread {
int total = 0;
public void run() {
synchronized (this) {
System.out.println("child thread starts calculation"); //--> 1
for (int i=0; i<=100; i++) {
total = total + i;
}
System.out.println("child thread trying to give notification"); //--> 2
this.notify();
}
}
}
sample 2)
public class Main{
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread();
t.start();
System.out.println("X"); //--> 1
synchronized(t) {
System.out.println("starting to wait"); //--> 2
t.wait(10000);
System.out.println("waiting on t"); //--> 3
}
System.out.println("Y"); //--> 4
}
}
sample 3)
public class Main{
public static void main (String[] args) throws InterruptedException {
Thread t = new Thread() {public void run()
{System.out.println("I am the second thread.");}};
t.start();
System.out.println("X"); //--> 1
synchronized(t) {
Thread.sleep(4000);
System.out.println("starting to wait"); //--> 2
t.wait(10000);
System.out.println("waiting on t"); //--> 3
}
System.out.println("Y"); //--> 4
}
}
In sample 1)
main thread goes in waiting state forever as it has called b.wait() method and there is no thread to provide notify() or notifyAll() on object b. There was child thread that has already been terminated before main thread called b.wait() method.
This output is what I expected.
In sample 2)
main thread goes in waiting state for 10 seconds (t.wait(10000);) after printing
X
starting to wait
after 10 seconds main thread executes
waiting on t
Y
This is also my expected output.
In sample 3)
main thread is NOT going in waiting state (t.wait(10000);) even though it is sure that child thread would have been terminated by the time main thread called t.wait(10000);
So why it didn't wait ? and straightaway executed
starting to wait
waiting on t
Y
This is NOT my expected output.
For the first two examples your expectations seem correct. In the third example it seems reasonable to expect that t will finish before the main thread starts waiting, and then the main thread will hang until it times out.
But as you observed, that isn't what happens.
A waiting thread doesn't stop waiting unless interrupted or notified (except for spurious wake ups, but those are the result of unpredictable race conditions; the behavior in the posted code happens reliably, so I think spurious wakeups can be excluded here).
Since there is nothing interrupting the main thread, and its wait is cut short and we've ruled out spurious wakeups, it must be receiving a notification. There is only one thing that can provide the notification, and that is the t thread.
For t to notify the main thread it must have been alive at the time that t started waiting. So what is keeping it around?
There is some not-well-known behavior that occurs when a thread terminates. The API documentation for Thread.join says:
This implementation uses a loop of this.wait calls conditioned on this.isAlive. As a thread terminates the this.notifyAll method is invoked. It is recommended that applications not use wait, notify, or notifyAll on Thread instances.
What happens is:
1) t prints its output and is on the way out of its run method.
2) There is a race between t and the main thread to acquire the lock on t. t needs it to call notifyAll, main needs it to enter the synchronized block. The main thread happens to grab the lock first.
3) t hangs around until it can acquire the lock.
4) The main thread enters the wait method (releasing the lock).
5) The t gets the lock and calls t.notifyAll.
5) The main thread is notified and leaves the wait method (reacquiring the lock).
Some lessons:
Don't synchronize on threads (this is a good example of why the API docs say not to do this, here you inadvertently delayed a thread from dying in a timely fashion).
If a thread isn't waiting, it doesn't get notified. If a thread starts waiting after the notification has already happened, that notification is lost.
Don't rely solely on notifications (it makes your code vulnerable to race conditions), instead use notifications along with some condition that the other thread can set. Call wait in a loop with a test condition. If you see the Thread.join source code, it is a good example, it looks something like:
while (isAlive()) {
wait(0);
}
Don't sleep while holding a lock. It makes the system less responsive for no benefit.
Be very careful about making assumptions about the order things happen in.
Below is my sample code, when my a.start() called it should create a thread and print "Run" immediately. But why does is called after printing "begin" 20 times.
How does thread "a" decide that it doesn't have to call run() immediately.
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
Thread.sleep(1000);
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
Output:
BeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBeginBegin
Run
End
I am little confused about the behavior of thread.
In my opinion "run" should be printed before "begin" because it get printed before the join() method is called, and at the time of join method called thread "a" must have finished its execution and calling join must be useless at that point.
Calling start() on a thread doesn't necessarily triggers the execution of its run() method immediately. Your thread is marked as started but the main thread pursues its execution into the for loop. Then the JVM is switching to your thread once the main thread reaches the sleep() statement.
You start the thread, then immediately do some printing, then sleep. Looking at your code I would actually expect to see Begin before Run because the thread is being started in the background, concurrently to your main thread going on with its work. Futhermore, the print method is synchronized so you repeatedly acquire that lock in a loop, giving even less chance to the second thread to interject.
I have tried your code with Thread.sleep eliminated, both with and without the join call. The behavior is the same in both cases: Run comes at the end most of the time and occasionally manages to get interleaved between the Begin words. Everything exactly as expected by the simple model of concurrency with synchronized blocks.
Here is a slight variation on your code which reliably prints Run before everything else, whether you call the join method or not. All that changed is the position of the sleep call.
public class JoinTest implements Runnable
{
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
Thread.sleep(1000);
for (int i = 0; i < 20; i++) {
System.out.print("Begin");
}
a.join();
System.out.print("\nEnd");
}
public void run() {
System.out.print("\nRun");
}
}
The start() method calls the thread's run() method, although this takes a little time, which may just be enough for some or all of your 'Begin' loops to complete. When I run this on my machine the 'Run' output appears between the first and second 'Begin'. Try outputting with timestamps so you can see how long your machine is taking to execute each command:
public class JoinTest implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread a = new Thread(new JoinTest());
a.start();
for (int i = 0; i < 20; i++) {
System.out.println("Begin " + System.nanoTime());
}
Thread.sleep(1000);
a.join();
System.out.println("End " + System.nanoTime());
}
public void run() {
System.out.println("Run " + System.nanoTime());
}
}
Calling a.join() at that point ensures that you will always see 'Run' output before 'End', as join() waits for the thread to complete.
I have tried many scenarios with join(), "run" always get printed after "begin" but when i remove the join statement "run" always get printed before "begin". Why?
Because it's allowed. That's why. As soon as you call .start(), you have two threads. Untill your program calls a synchronization methods like .join() it's entirely up to the JVM implementation and the operating system to decide which thread gets to run when.
The a.join() call from your main thread forces the main thread to wait until the a thread has completed its run() method.
Without the a.join() call, the Java Language Specification permits the a thread to complete its work before a.start() returns in the main thread, and it permits the main thread to reach the end of the main() function before the a thread even begins to run, and it permits anything in between to happen.
It's entirely up to the JVM and the OS.
If you want to take control of the order in which things happen, then you have to use synchronized blocks, and synchronization objects and method (e.g., .join()).
But beware! The more you force things to happen in any particular order, the less benefit your program will get from using threads. It's best to design your program so that the threads can function independently of one another most of the time.
I have a simple test with thread:
package Thread;
class Sum extends Thread {
int low, up, S;
public Sum(int a, int b) {
low = a;
up = b;
S = 0;
System.out.println("This is Thread " + this.getId());
}
#Override
public void run() {
for (int i = low; i < up; i++) {
S += i;
}
System.out.println(this.getId() + ":" + S);
}
}
public class Tester {
public static void main(String agrs[]) {
Sum T1 = new Sum(1, 100);
T1.start();
Sum T2 = new Sum(10, 100);
T2.start();
System.out.println("Main process terminated");
}
}
but i don't understand when was run() method executed, it return same that:
This is Thread 8
This is Thread 9
Main process terminated
9:4905
8:4950
It's mean the run() method was executed after T1 and T2 start. I still think that when start() method was invoked the run() will be execute. Thank for advance!
When you call start() on the thread object , it invokes the run() method.
When in doubt , read the documentation: Thread#start():
causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
Suggested Reading:
Why we call Thread.start() method which in turns calls run method?
Oracle tutorial
Why is run() not immediately called when start() called on a thread object in java
The start() method creates a new thread, that executes the run() method.
From Documentation:
Causes this thread to begin execution; the Java Virtual
Machine calls the run method of this thread.
When we invoke Thread.start JVM creates a new native thread and then calls Thread.run which causes this Thread to begin execution. Thread.run is invoked by JVM asynchroneously, so these 3 lines
Main process terminated
9:4905
8:4950
might appear in any order.
The thread scheduler is selecting which thread for run. It can be random selection if you are not giving any priority for the thraed.
Here the thread scheduler will select thread and it will work in two separate stack space as two independent thread process. So thread T1 starts before thread T2 and there is no sleep, no wait, no join the both will give output at same time.
for more details please visit http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#start%28%29
you can understand it more clearly if you use remaining functions of Thread like sleep(), join(), wait() etc...
In Java if I have a class that creates threads from the constructor (by calling some functions of that class) and I create an object of that class in my main method. Does the main method wait until all the threads are done or does it continue to the next line?
for example:
public static void main(String[] args) {
WorksWithThreads obj = new WorksWithThreads ( );
//does something else - does this line happen after all the 9 threads finished their job?
}
class WorksWithThreads(){
public WorksWithThreads(){
for(int i=0;i<9;i++)
WithThread tread= new WithThread();
}
private static class WithThread extends Thread {
public WithThread () {
run();
}
public void run(){
//does something
}
}
}
I hope I was not too confusing.. Thank you in advance..
Shiran
If you actually spawn new Threads your main method would continue right after finishing spawning (but before the threads end, assuming they run for sometime)
BUT you are not spawning threads. You are creating instances of the Thread class. To actually spawn new threads you'd have to call start. Calling run() as you do is just a normal method call and processing will only continue after it finished.
You might want to work through the official tutorial about this topic.
No. The very point of threads is that they don't halt execution of the thread that spawns them. main() will continue executing as soon as WorksWithThreads has finished spawning all its threads, but the threads it spawns will execute at the same time as the rest of main.
Yes it will run after the 9 threads are created.Here you have not even start those 9 threads.So before they are executed next line in main will be executed
I have a portion of code dealing with threads and I want to understand its function in detail. The run method is empty in my example, but lets assume it has some operations to do on a global variable:
import java.io.File;
public class DigestThread extends Thread {
private File input;
public DigestThread(File input) {
this.input = input;
}
public void run() {
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
File f = new File(args[i]);
Thread t = new DigestThread(f);
t.start();
}
}
}
After creating a thread and starting it, will it wait to finish the tasks in the run method before creating/running another thread ?
second question
if a variable has declared in run method that means it will be declared many times because every thread created will do the task in run method , is every thread handles its own varible although variable in each thread are same ?
will it waitng for finish the tasks in run method to creat another
method ?
No. That's the whole point of Multithreading. Every thread has it's own stack of execution. So, when you start a thread, it enters the run() method, and executes it in a different stack, and at the same time the main thread continues execution, in it's own stack.
After that, main thread, can spawn another thread. Thus all the threads run simultaneously, but of course, one at a time, sharing the CPU amongst them, based on the specific CPU allocation algorithm being used.
It's not possible to write down all the details about the execution process of multiple threads here. I would rather suggest to read some tutorials or search for some online resources, regarding the concept of Multithreading. Once clear in concept, move ahead with the implementation in Java.
Here's some tutorials links you can start with: -
Thread Wiki Page
SO Multithreading Wiki Page
Concurrency - Oracle Tutorial
http://www.vogella.com/articles/JavaConcurrency/article.html
Once you start a thread, it will run in a separate thread and the main() thread will continue (it may end before the child thread ends).
If you want the thread to finish before main then you can use the Thread.join method on thread to wait for it.
First, Thread is a single sequential flow of control within a program.
We can execute more than one thread in a program, but there is a life cycle, where you can find out how threads work...
Whenever we call the start() method of Thread it automatically calls the overriden method public void run() and executes the code of the run() method...
Here is a simple example of Thread in Java with ABC and XYZ thread classes
/* Write a program to print having two Thread Class 1) ABC with 1 second 2) XYZ 2 second. 10 times with Extend Constructor */
class ABCThreadConstructor extends Thread {
ABCThreadConstructor(String name) {
super(name);
}
public void run() {
try {
for(int i = 0; i < 10; i++) {
System.out.println("ABC");
Thread.sleep(1000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class XYZThreadConstructor extends Thread {
XYZThreadConstructor(String name) {
super(name);
}
public void run() {
try{
for(int i = 0; i < 10; i++) {
System.out.println("XYZ");
Thread.sleep(2000);
}
} catch(InterruptedException ie) {
System.out.println("Interrupted Exception : "+ie);
}
}
}
class AbcXyzThreadConstructorDemo {
public static void main(String args[]) {
ABCThreadConstructor atc = new ABCThreadConstructor("ABCThreadConstructor");
System.out.println("Thread Name : " + atc.getName());
atc.start();
XYZThreadConstructor xtc = new XYZThreadConstructor("XYZThreadConstructor");
System.out.println("Thread Name : " + xtc.getName());
xtc.start();
}
}
Assuming your question is "After creating a thread and starting it, will the program wait for the thread to finish its run method before creating another thread?"
If that's the case, No the program will not wait. t.start() kicks off the thread and it gets its own chunk of memory and thread priority to run. It will do its operations and then exist accordingly. Your main thread will start the number of threads specified in args before terminating.
If you need the application to wait on the thread then use t.join(). That way the parent thread (the one that runs main) will be joined to the child thread and block until its operation is complete. In this case it sort of defeats the purpose of threading but you can store the thread ID for whatever logic you need and join() later.