Stop方法不推荐使用,我给个具体的例子:
public class DeprecatedStop extends Object implements Runnable {
public void run() {
int count = 0;
while ( count <20 ) {
System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
// ignores
}
}
// the code maybe not executed
System.out.println("stoped");
}
public static void main(String[] args) {
DeprecatedStop ds = new DeprecatedStop();
Thread t = new Thread(ds);
t.start();
try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
// Abruptly stop the other thread in its tracks!
t.stop();
}
}
可能的运行结果:
Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6
可以发现程序中的打印stoped并没有执行,所以说如果在程序中有其他操作,如果线程突然stop是会带来严重的影响的。所以怎么也应该使用该操作。当
然如果是我上面的程序代码突然stop的影响其实是没有的,但是如果是其他打开文件最后需要释放或者什么的就会带来严重的影响了。
如何在程序中对其进行停止呢?
public class AlternateStop extends Object implements Runnable {
private volatile boolean stopRequested;
private Thread runThread;
public void run() {
runThread = Thread.currentThread();
stopRequested = false;
int count = 0;
while ( !stopRequested ) {
System.out.println("Running ... count=" + count);
count++;
try {
Thread.sleep(300);
} catch ( InterruptedException x ) {
Thread.currentThread().interrupt(); // re-assert interrupt
}
}
System.out.println("stoped");
}
public void stopRequest() {
stopRequested = true;
if ( runThread != null ) {
runThread.interrupt();
}
}
public static void main(String[] args) {
AlternateStop as = new AlternateStop();
Thread t = new Thread(as);
t.start();
try {
Thread.sleep(2000);
} catch ( InterruptedException x ) {
// ignore
}
as.stopRequest();
}
}
可能的运行结果如下:
Running ... count=0
Running ... count=1
Running ... count=2
Running ... count=3
Running ... count=4
Running ... count=5
Running ... count=6
stoped
这样我们就解决了强制 stop的问题。