12

Here are my two classes:

public class Firstclass {
    public static void main(String args[]) throws InterruptedException {
        System.out.println("Main start....");
        Secondclass t1 = new Secondclass();
        t1.setName("First Thread");
        Secondclass t2 = new Secondclass();
        t2.setName("Second Thread");
        t1.start();
        t2.start();
        System.out.println("Main close...");
    }
}

and

public class Secondclass extends Thread {
    @Override
    public void run() {
        try {
            loop();
        } catch(Exception e) {
            System.out.println("exception is" + e);
        }
    }

    public void loop() throws InterruptedException {
        for(int i = 0; i <= 10; i++) {
            Thread t = Thread.currentThread();
            String threadname = t.getName();
            if(threadname.equals("First Thread")) {
                Thread.sleep(1000);
            } else {
                Thread.sleep(1500);
            }
            System.out.println("i==" + i);   
        }
    }
}

Now when I run Firstclass then the output is:

Main start....
Main close...
i==0
i==0
i==1
i==1
i==2
i==3
i==2
i==4
i==3
i==5
i==6
i==4
i==7
i==5
i==8
i==9
i==6
i==10
i==7
i==8
i==9
i==10

My first question is: I want to know why both threads are still running even though the main method have finished?

My second question is: can anybody explain to me what the difference is between methods join and synchronized?

Felix Glas
  • 15,065
  • 7
  • 53
  • 82
TruePS
  • 493
  • 2
  • 12
  • 33

6 Answers6

3

I want to know that even though the main method is closed How are both threads still running?

The JVM will exit once the last non-jvm thread terminates. this means that if any of the threads you create is still running, the jvm will not shutdown. daemon threads are threads that do not prevent the JVM from shutting down. normally you'd use them for some background tasks which you dont want keeping your application up if the user requested it to shut down.

A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

You can use the setDaemon() method to change the Thread daemon properties. By default, every thread that a user create is a normal (non-daemon) thread, unless you explicitly call setDaemon() method.

explain me what is the difference between join method and synchronized

Synchronization is a locking mechanism that allows two threads to not step on each other i.e. synchronization is used to provide proper access to shared resources by multiple threads with the help of locking mechanism.
On the other hand join() method call allows one thread to wait for the completion of another thread.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
  • so you are saying that main method is dies after thread t1 and t2 completes. – TruePS Mar 03 '14 at 13:23
  • 1
    I am saying that JVM process wont terminate until t1 and t2 completes. Main method will die off. You can make it wait for t1 an t2 by calling join method. – Ankur Shanbhag Mar 03 '14 at 13:26
3

Your first question,

When main method is called by default one main thread is created. And main thread is a non-dameon thread. When threads created by the main method it inherits it's parant's property. That means they are all non-daemon threads. As you know JVM waits until all non-daemon threads to complete. So it will executes even after the main thread completes.

See here : daemon vs non-daemon Java Stack for each thread creation

and your second question: join method joins the currently running thread at the end of the thread which is calling the join method. That means the current thread will be stopped and it start after the thread referenced by the join method.

Synchronization stops two threads executing the same code at the same time.

Sivaranjani D
  • 512
  • 4
  • 16
  • Now I am officially confused because the other people have answered that main thread dies after every other thread dies and you are saying that main method dies and still others threads are executing. – TruePS Mar 03 '14 at 13:21
  • 1
    main threads wont wait until all it's child threads to complete. see my post http://technicalminds.in/core-java/will-main-thread-waits-child-threads/ with example proof. – Sivaranjani D Mar 07 '14 at 09:29
2

I want to know that even though the main method is closed How are both threads still running?

Your main() method was run by a separate thread, which start another two threads (First ad Second). All Threads are not depend on each other, so, main thread can print the line below the starting line of other threads.

My second question is can anybody explain me what is the difference between join method and synchronized?

join() means waiting for a thread to complete. This is a blocker method. synchronized is a keyword to denote that, multiple thread can't access a synchronized block/method synchronously.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105
  • @ Kugathasan I didn't understand your answer kindly tell me when will the main method() die in case of above program? – TruePS Mar 03 '14 at 13:26
2

join If you have a thread B that can't do its work until another thread A has completed its work, then you want thread B to "join" thread A.

synchronized When we use threads, we usually need to use some synchronization somewhere to make sure our methods don't interrupt each other at the wrong time and mess up our data. Generally, any time more than one thread is accessing mutable (changeable) data, you synchronize to protect that data, to make sure two threads aren't changing it at the same time (or that one isn't changing it at the same time the other is reading it, which is also confusing).

Saurabh Jain
  • 1,600
  • 1
  • 20
  • 30
  • Hope this question helps you clear your confusion: http://stackoverflow.com/questions/8784333/can-the-main-thread-die-before-the-child-thread – Saurabh Jain Mar 04 '14 at 07:23
2

There are two types of threads user and daemon. So if you want your program to exit make your thread a daemon.

Example

Thread t = new Thread();
t.setDaemon(true);

The process terminates when there are no more user threads.

To your second Question:

Join is to be used only when you need to ensure that the thread dies & you have nothing to do after that

Synchronization is for inter-thread-communication

Vinayak Pahalwan
  • 2,915
  • 4
  • 26
  • 34
  • you said if i make my thread daemon then main method() dies,In the above case all methods are user methods so when will the main method die? – TruePS Mar 03 '14 at 13:25
0

Your main thread is not closed -

      // ...
      System.out.println("Main close...");
      // <--- Your main method is here while all the other threads complete (sort of).
     }

On part 2 of your question - There is no connection between join and synchronized. They are almost opposite.

  • join - Wait for the thread to complete before resuming.
  • synchronized - Only one thread can enter here, all others must wait.
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • @ Sivaranjani D is saying the opposite here.Kindly tell me how is he wrong? – TruePS Mar 03 '14 at 13:26
  • 4
    -1. Method `main` will *not* wait until all threads have finished unless you explicitly use `join`. The JVM will not end the process until all user threads have finished though. – Felix Glas Mar 03 '14 at 13:33
  • @snps - To me *The JVM will not end the process until all user threads have finished* is equivalent to an implicit join at the end of `main`. I accept that there is a subtle difference but are you sure it is worth a downvote? – OldCurmudgeon Mar 03 '14 at 13:50
  • @TruePS - I think SivaranjaniD is saying the same as me in different words. – OldCurmudgeon Mar 03 '14 at 13:52
  • @OldCurmudgeon Saying there's an implicit join at the end of `main` may imply that the main thread is still running/waiting and that it is still joinable. – Felix Glas Mar 03 '14 at 15:02
  • @OldCurmudgeon you are saying that main method closes after thread t1 and t2 completes but he is saying that main method closes or die and still other threads are running,how is this possible consider main method(0 as a parent thread so how can child thread works if parent thread has already dies. – TruePS Mar 04 '14 at 05:03
  • 1
    @TruePS - Because the `main` **method** is called by the main **thread**. The `main` **method** completes but the `main` **thread** will wait until all other non-daemon threads it has created are dead before exiting the VM. – OldCurmudgeon Mar 04 '14 at 08:35
  • @ OldCurmudgeon so what you said above is not true that means // <--- Your main method is here while all the other threads complete (sort of). } This statement is wrong.Am I right? – TruePS Mar 04 '14 at 09:36
  • @TruePS - It is nearly wrong - which is why I added the *sort of*. It demonstrates why you are getting the "Main close ..." printout before the "i==..." printouts but actually we are outside `main` but still inside the `main` **thread**. – OldCurmudgeon Mar 04 '14 at 10:12
  • @OldCurmudgeon The main **thread** will *not* wait until all other non-daemon threads it has created are dead before exiting, this is wrong. The specification says that the JVM will wait until all non-daemon threads have terminated before exiting, it doesn't make any distinction about the main thread. The main thread and the JVM are different things. The main thread is spawned by the JVM at start and it can terminate without the JVM exiting. – Felix Glas Mar 07 '14 at 14:49
  • 1
    @TruePS As Java is a managed language all binary code is executed on the *Java Virtual Machine* which keeps track of which threads that is currently running and which that are daemon-threads etc. Threads spawned from the main thread are not considered "children" of the main thread, instead they are executed as separate threads monitored by the JVM. It's fully possible for the main thread to terminate while other threads are still running and the JVM will then wait for all non-daemon threads to finish before exiting. – Felix Glas Mar 07 '14 at 14:59
  • 1
    @Snps I hope your comment will be posted as an answer. Thanks. – hqt Sep 27 '19 at 16:50