hi there, hope that u all r fine.here is the programme which has a output which i dont expect so please help me out.
class Threads extends Thread{ public void run(){ System.out.println(Thread.currentThread()+"is going to start"); try{sleep(1000); }catch(InterruptedException e){ System.out.println("Exception in"+Thread.currentThread()+" was Caught"); } } } class TestThreads{ public static void main(String []args){ Threads[] t1={ new Threads(),new Threads()}; for (int i=0;i<t1.length;i++){ t1[i].start(); //t2.start(); t1[i].interrupt(); System.out.println(t1[i]+" is interrupted:-"+t1[i].isInterrupted()); } } } /*output: Thread[Thread-0,5,main] is interrupted:-true Thread[Thread-1,5,main] is interrupted:-true Thread[Thread-0,5,main]is going to start Thread[Thread-1,5,main]is going to start Exception inThread[Thread-0,5,main] was Caught Exception inThread[Thread-1,5,main] was Caught question :- my question is that why interrupted statement comes first,rather it should come later? hope that you ppl would help me out. thanks in advance with regards kumar abhay*/
Dan Cranmer
Greenhorn
Joined: May 24, 2000
Posts: 24
posted
0
There is some overhead in starting a Thread and then the JVM has to call the run method, all of which takes longer than dropping to the next method in the loop which is the interrupt. A sleep of 1 millisecond after the start is enough time for the thread to get started before the interrupt. [ July 26, 2002: Message edited by: Dan Cranmer ]
You can not reliably say t1.start() t1.interrupt() because start() does not wait till the thread is started. the start command tells the thread to start but it returns before the thread is started. Because t1 is a seperate thread and it may or may not be started by the time you try to interrupt it. maybe this will work t1.start(); while(!t1.isAlive()); t1.interrupt();