pyqt stop停止线程_面试官:如何终止线程?有几种方式?
在 Java 中有以下 3 種方法可以終止正在運行的線程:
第一種:使用標志位終止線程
使用標志位終止線程就是定義一個boolean型的標志位 ,在線程的run方法中根據這個標志位是為true還是為false來判斷是否終止,這種情況多用于while循環中。
class StopThread extends Thread { //標志位private boolean flag = true;@Overridepublic synchronized void run() {while (flag) {System.out.println(Thread.currentThread().getName()+"---我是子線程");}}/** * @methodDesc: 功能描述:(終止線程) */public void stopThread() {flag = false;System.out.println(getName()+"線程被終止掉了");}}/** @classDesc: 功能描述:(演示終止線程效果) */public class StopThreadDemo {public static void main(String[] args) {StopThread stopThread1 = new StopThread();StopThread stopThread2 = new StopThread();stopThread1.start();stopThread2.start();for (int i = 0; i < 50; i++) {System.out.println("------我是主線程-----"+i);if(i==30) {stopThread1.stopThread();stopThread2.stopThread(); }}}}第二種: 使用 stop() 終止線程(不安全)
雖然使用stop() 方法可以停止一個正在運行的線程,但是這個方法是不安全的,而且該方法已被棄用。
棄用stop()方法的原因:
第三種: 使用interrupt方法中斷線程
使用 interrupt() 方法中斷線程時并不會立即終止線程,而是通知目標線程,告訴它有人希望你終止。至于目標線程收到通知后會如何處理,則完全由目標線程自行決定。理解這一點很重要,如果中斷后,線程立即無條件退出,那么就會和 stop() 方法沒有任何區別,會導致線程不安全問題。
首先我們先來看一個使用 interrupt() 中斷線程的例子:
public class InterruptThread extends Thread{@Override public void run() { for(int i = 0; i <= 10000; i++) { System.out.println("i=" + i); } } public static void main(String[] args) { try { InterruptThread interruptThread = new InterruptThread(); interruptThread.start(); Thread.sleep(100); interruptThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }運行結果如下:
從輸出的結果可以發現調用 interrupt 方法并沒有停止掉線程interruptThread中的處理邏輯,也就是說即使線程被設置為了中斷狀態,但是這個中斷并沒有起到任何作用,那么怎樣才能停止線程呢?
這就需要使用到 isInterrupted() 方法了:
public boolean Thread.isInterrupted() //判斷是否被中斷所以如果希望線程在中斷后停止,就應該先判斷線程是否被中斷,然后在執行中斷處理代碼:
public class InterruptThread extends Thread{@Override public void run() { for(int i = 0; i <= 10000; i++) { //判斷是否被中斷 if(Thread.currentThread().isInterrupted()){ //處理中斷 break; } System.out.println("i=" + i); } } public static void main(String[] args) { try { InterruptThread interruptThread = new InterruptThread(); interruptThread.start(); Thread.sleep(100); interruptThread.interrupt(); } catch (InterruptedException e) { e.printStackTrace(); } } }運行結果:
在上面這段代碼中,我們增加了 Thread.isInterrupted() 來判斷當前線程是否被中斷了,如果線程被中斷,則退出 for 循環,結束線程。
來源:csdn
作者:有頭發的代碼匠
總結
以上是生活随笔為你收集整理的pyqt stop停止线程_面试官:如何终止线程?有几种方式?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sas table将缺失值计入百分比_S
- 下一篇: cad抛物线曲线lisp_曲线的转弯半径