Thread currentThread=Thread.currentThread();
public void run()
{
while(!shutdown)
{
try
{
System.out.println(currentThread.isAlive());
Thread.interrupted();
System.out.println(currentThread.isAlive());
if(currentThread.isAlive()==false)
{
shutdown=true;
}
}
catch(Exception e)
{
currentThread.interrupt();
}
}
}
});
thread.start();
Run Code Online (Sandbox Code Playgroud) 我试图阻止一个线程,但我不能这样做:
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 …Run Code Online (Sandbox Code Playgroud) 我试图在以下代码中终止线程:
public synchronized void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
this.scan();
this.distribute();
this.wait();
}
} catch (InterruptedException e) {}
}
public void cancel() {
this.interrupt();
}
Run Code Online (Sandbox Code Playgroud)
但线程不会终止.我使用了调试器并发现在命令之后this.interrupt(),线程没有被中断(我对表达式进行了监视this.isInterrupted()并保持不变false).任何人都知道为什么这个线程不会被打断?
问题已经找到.原来这个帖子有两个实例.我附上导致这个问题的有问题的代码:
/* (class Detector extends Thread) */
Detector detector = new Detector(board);
...
Thread tdetector = new Thread(detector); /* WRONG!!! */
...
tdetector.start();
...
Run Code Online (Sandbox Code Playgroud)