pyqt stop停止线程_面试官:如何终止线程?有几种方式?
在 Java 中有以下 3 種方法可以終止正在運(yùn)行的線程:
第一種:使用標(biāo)志位終止線程
使用標(biāo)志位終止線程就是定義一個(gè)boolean型的標(biāo)志位 ,在線程的run方法中根據(jù)這個(gè)標(biāo)志位是為true還是為false來(lái)判斷是否終止,這種情況多用于while循環(huán)中。
class StopThread extends Thread { //標(biāo)志位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() 方法可以停止一個(gè)正在運(yùn)行的線程,但是這個(gè)方法是不安全的,而且該方法已被棄用。
棄用stop()方法的原因:
第三種: 使用interrupt方法中斷線程
使用 interrupt() 方法中斷線程時(shí)并不會(huì)立即終止線程,而是通知目標(biāo)線程,告訴它有人希望你終止。至于目標(biāo)線程收到通知后會(huì)如何處理,則完全由目標(biāo)線程自行決定。理解這一點(diǎn)很重要,如果中斷后,線程立即無(wú)條件退出,那么就會(huì)和 stop() 方法沒(méi)有任何區(qū)別,會(huì)導(dǎo)致線程不安全問(wèn)題。
首先我們先來(lái)看一個(gè)使用 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(); } } }運(yùn)行結(jié)果如下:
從輸出的結(jié)果可以發(fā)現(xiàn)調(diào)用 interrupt 方法并沒(méi)有停止掉線程interruptThread中的處理邏輯,也就是說(shuō)即使線程被設(shè)置為了中斷狀態(tài),但是這個(gè)中斷并沒(méi)有起到任何作用,那么怎樣才能停止線程呢?
這就需要使用到 isInterrupted() 方法了:
public boolean Thread.isInterrupted() //判斷是否被中斷所以如果希望線程在中斷后停止,就應(yīng)該先判斷線程是否被中斷,然后在執(zhí)行中斷處理代碼:
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(); } } }運(yùn)行結(jié)果:
在上面這段代碼中,我們?cè)黾恿?Thread.isInterrupted() 來(lái)判斷當(dāng)前線程是否被中斷了,如果線程被中斷,則退出 for 循環(huán),結(jié)束線程。
來(lái)源:csdn
作者:有頭發(fā)的代碼匠
總結(jié)
以上是生活随笔為你收集整理的pyqt stop停止线程_面试官:如何终止线程?有几种方式?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: sas table将缺失值计入百分比_S
- 下一篇: PHP随机配菜_PHP+JS三级菜单联动