e093. stopping a thread.txt
来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 30 行
TXT
30 行
The proper way to stop a running thread is to set a variable that the thread checks occasionally. When the thread detects that the variable is set, it should return from the run() method.
Note: Thread.suspend() and Thread.stop() provide asynchronous methods of stopping a thread. However, these methods have been deprecated because they are very unsafe. Using them often results in deadlocks and incorrect resource cleanup.
// Create and start the thread
MyThread thread = new MyThread();
thread.start();
// Do work...
// Stop the thread
thread.allDone = true;
class MyThread extends Thread {
boolean allDone = false;
// This method is called when the thread runs
public void run() {
while (true) {
// Do work...
if (allDone) {
return;
}
// Do work...
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?