• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

Thread running sequence

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all..

I am trying this code:

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


output

D:\>java v
java.lang.IllegalThreadStateException
go


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

 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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) .
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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()


 
Acetylsalicylic acid is aspirin. This could be handy too:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic