如何在Java中中断/停止线程? [英] How interrupt/stop a thread in Java?
问题描述
我正在尝试停止线程,但我不能这样做:
I'm trying to stop a thread but I can't do that :
public class Middleware {
public void read() {
try {
socket = new Socket("192.168.1.8", 2001);
// code ..
Scan scan = new Scan();
thread = new Thread(scan);
thread.start();
} catch (UnknownHostException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
class Scan extends Thread {
public void run() {
while (true) {
try {
// my code goes here
} catch (IOException ex) {
thread.currentThread().interrupt();
}
}
}
}
public void stop() {
Thread.currentThread().interrupt();
}
// get and setters
}
因此,即使我调用方法"stop",线程也不会停止. 它一直活着.
So, even when i call the method 'stop' the thread don't stop. It keeps alive.
如何中断/停止该线程?
How can I interrupt/stop this thread ?
更新 (@小方法)
private void tb_startActionPerformed(java.awt.event.ActionEvent evt) {
Middleware middleware = new Middleware();
if (tb_start.getText().equals("Start")){
tb_start.setText("Stop");
// starting to read rfid tags
middleware.read();
}else{
tb_start.setText("Start");
// stop reading rfid tags
middleware.stop();
}
}
中间件类:
public class Middleware {
private Scan scan;
public void read() {
scan = new Scan();
scan.start();
}
private class Scan extends Thread {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("reading...");
}
}
}
public void stop() {
if (scan != null) {
scan.interrupt();
}
}
}
但是当我尝试停止线程时,它没有.
But when I try to stop the thread, it doesn't.
上面的代码可能出什么问题了?
What could be wrong in the code above ?
推荐答案
实际上没有理由需要使用volatile
标志.相反,只需使用 isInterrupted()
.另外,为什么还要将Scan
线程对象包装在另一个线程对象中?对我来说,这似乎完全没有必要.
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.
这是你应该做的
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();
}
}
}
这是一个示例 .另外,我不建议扩展Thread
.
Here's an example. Also, I wouldn't recommend extending Thread
.
这篇关于如何在Java中中断/停止线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!