How interrupt/stop a thread in Java?
Simply return;
from your while and the thread will die, no need to call stop() or interrupt(). If you want to do it externally then use this pattern and call requestStop()
.
class Scan extends Thread {
private volatile stop = false;
public void run() {
while (!stop) {
try {
// my code goes here
} catch (IOException ex) {
stop = true;
}
}
}
public void requestStop() {
stop = true;
}
}
There's really no reason you need to use a volatile
flag. Instead, just query the thread for its state with isInterrupted()
. Also, why are you wrapping your Scan
thread object in another thread object? That seems completely unnecessary to me.
Here' what you should be doing
public class Middleware {
private Scan scan;
public void read() {
try {
// do stuff
scan = new Scan();
scan.start();
} catch (UnknownHostException ex) {
// handle exception
} catch (IOException ex) {
// handle exception
}
}
private class Scan extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
// my code goes here
} catch (IOException ex) {
Thread.currentThread().interrupt();
}
}
}
}
public void stop() {
if(scan != null){
scan.interrupt();
}
}
}
Here's an example. Also, I wouldn't recommend extending Thread
.