Two Laptop Bag
The moose likes Threads and Synchronization and the fly likes Thread running sequence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Thread running sequence" Watch "Thread running sequence" New topic

Thread running sequence

swati aole

Joined: May 02, 2009
Posts: 9
hi all..

I am trying this code:

class v extends Thread{
public void run() {
System.out.print("go ");
public static void main(String [] args){
Thread t1 = new v();
Thread t2 = (t1);
catch(Exception e)


D:\>java v

I am confused from this output ... If we invoked start() again on the same Thread obj... it will throw IllegalThreadStateException.. but how come after the exception is thrown it is printing the "go"... the program should get terminated.
So if the firstly started thread gets the chance to run it should print "go " and then the exception or only the exception... how come it is printing a message from run() after an exception is thrown..???
please send some explanation..Thanks

Vijitha Kumara

Joined: Mar 24, 2008
Posts: 3902

First, the given order of the output may vary on different executions.

but how come after the exception is thrown it is printing the "go"... the program should get terminated.

The main method will terminate (where the exception occurs). But the Thread t1 runs independantly of the main method(rather main thread) .

[How to ask questions] [Twitter]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
The main thread catching the exception does indeed terminate the program. However, all that logic is happening in the main thread. Until the program actually terminates, the other thread is still active and running. This is one possible sequence of events:

  1. Thread t1 starts
  2. Second call to start() throws exception
  3. Exception caught by main thread's run()
  4. Thread t1's run() prints "go "
  5. Main thread calls System.exit()

subject: Thread running sequence
jQuery in Action, 3rd edition