IntelliJ Java IDE
The moose likes Threads and Synchronization and the fly likes asking about threads!!!!1 Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "asking about threads!!!!1" Watch "asking about threads!!!!1" New topic
Author

asking about threads!!!!1

kumar abhay
Ranch Hand

Joined: Oct 02, 2001
Posts: 53
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
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 ]
Mr. C Lamont Gilbert
Ranch Hand

Joined: Oct 05, 2001
Posts: 1158

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();
 
IntelliJ Java IDE
 
subject: asking about threads!!!!1
 
Threads others viewed
Reg. Some Thread basics
Dan's Question : Thread
Question in thread
stopping a thread
Thread synchronization
IntelliJ Java IDE