Stopping
a thread with Thread.stop causes it to release
all of the monitors that it has locked. If any of the objects previously
protected by these monitors were in an inconsistent state, the damaged objects
become visible to other threads, which might lead to unpredictable behavior.
How to stop the thread,
as stop() method is deprecated in java
1. Infinitely running thread can be stopped
using boolean variable.
class MyRunnable implements Runnable {
volatile boolean stopFlag=true;
public void run() {
int i = 0;
String
name = Thread.currentThread().getName();
while (true) {
if (stopFlag) {
try {
System.out.println(i++);
Thread.sleep(1000);
System.out.println("Please press enter key to stop
"+name);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
} else{
System.out.println(name+"
ended.");
break;
}
}
}
}
public class StopThread {
public static void main(String args[]) throws Exception {
MyRunnable
obj = new MyRunnable();
Thread
t = new Thread(obj,"Thread-1");
t.start();
String
name
= Thread.currentThread().getName();
System.out.println(name +" thread waiting to press
enter");
// Wait till read input
System.in.read();
// set stopFlag false
obj.stopFlag = false;
System.out.println(name+"
thread ended");
}
}
Output:
0
main thread waiting to press enter
Please press enter key to stop
Thread-1
1
Please press enter key to stop
Thread-1
2
main thread ended
Please press enter key to stop
Thread-1
Thread-1
ended.
2. Infinitely running thread can be stopped
using interrupt() method.
When
thread is interrupted, if it in waiting state caused by invocation of wait(),
sleep or join() method then its
interrupt status will be cleared and it will receive an InterruptedException.
class MyRunnable1 implements Runnable {
public void run() {
int i = 0;
String name = Thread.currentThread().getName();
try {
while (!Thread.currentThread().isInterrupted())
{
Thread.sleep(1000);
System.out.println(i++ + " press enter key to stop
"+ name);
}
} catch (InterruptedException e) {
System.out.println(name + " ended.");
}
}
}
public class StopThreadUsingInterrupt {
public static void main(String args[]) throws Exception {
MyRunnable1 obj = new MyRunnable1();
Thread t = new Thread(obj, "Thread#1");
t.start();
String name = Thread.currentThread().getName();
System.out.println(name + "
thread waiting to press enter");
System.in.read();
t.interrupt();
System.out.println(name + " thread ended.");
}
}
Output:
main thread waiting to press enter
0 press enter key to stop Thread#1
1 press enter key to stop Thread#1
2 press enter key to stop Thread#1
3 press enter key to stop Thread#1
4 press enter key to stop Thread#1
main thread ended.
Thread#1 ended.
No comments:
Post a Comment