I have a thread:
Thread t = new Thread(){
public void run(){
ServerSocketConnection scn = (ServerSocketConnection)
Connector.open("socket://:1234");
// Wait for a connection.
SocketConnection sc = (SocketConnection) scn.acceptAndOpen();
//do other operation
}
};
t.start();
Lets say no client is connecting to the Server, so this thread will be blocked.Now I want to kill the above thread t? How can I kill it?
Whether a thread is interrupted can be checked by the isInterrupted() method of Thread class. Another method, Thread. interrupted() returns the interrupt status and also clears it. A thread which is blocked to acquire an intrinsic lock (BLOCKED state) cannot be interrupted.
Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
interrupt() If any thread is in sleeping or waiting for the state then using interrupt() method, we can interrupt the execution of that thread by showing InterruptedException . A thread that is in the sleeping or waiting state can be interrupted with the help of interrupt() method of Thread class.
Thread.interrupt()
will not interrupt a thread blocked on a socket. You can try to call Thread.stop()
or Thread.destroy()
, but these methods are deprecated (edit: actually, absent in J2ME) and in some cases non-functional, for reasons you can read about here. As that article mentions, the best solution in your case is to close the socket that you're blocking on:
In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With