📄 e093. stopping a thread.txt
字号:
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -