Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can thread run after main method closes?

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?

like image 908
TruePS Avatar asked Mar 03 '14 12:03

TruePS


1 Answers

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.
like image 197
OldCurmudgeon Avatar answered Oct 07 '22 01:10

OldCurmudgeon