マルチスレッドを停止するいくつかの方法(詳細に説明)

方法1

終了フラグを使用して、スレッドを正常に終了させます。つまり、runメソッドが完了するとプロセスが終了します。

public class TestFlagStop implements Runnable{
    
    

	//1、设置一个标示位
	private boolean flag = true;
	
	@Override
	public void run() {
    
    
		int i = 0;
		while(flag) {
    
    
			System.out.println("run...Thread"+i++);
		}
	}
	
	//2、设置一个公共的方法停止线程,转换标志位
	public void stop() {
    
    
		this.flag = false;
	}

	public static void main(String[] args) {
    
    
		TestFlagStop testStop = new TestFlagStop();
		new Thread(testStop).start();
		
		for (int i = 0; i < 1000; i++) {
    
    
			System.out.println("main"+i);
			if(i==900) {
    
    
				//调用stop方法切换标志位,让线程停止
				testStop.stop();
				System.out.println("线程该停止了");
			}
		}
	}
}

方法2

スレッドを停止するために、古いJDKではThread.stop()メソッドが使用されていましたが、後でstop()メソッドが「廃止/期限切れ」としてマークされているため、このメソッドは非常に危険で安全ではないことがわかりました。 JDK ""メソッド、明らかに機能的に欠陥があります。ここで破棄してください。

方法2

スレッドを中断するには、interruptメソッドを使用します。

まず、for-breakと割り込みを使用してスレッドを停止します。

public class InterruptBreakStop extends Thread {
    
    
	@Override
    public void run() {
    
    
        for (int i = 0; i < 500000; i++) {
    
    
            if (this.isInterrupted()) {
    
    
                System.out.println("已经是停止状态了!我要退出了!");
                break;
            }
            System.out.println("i=" + (i + 1));
        }
        System.out.println("我被输出,如果此代码是for又继续运行,线程并未停止!");
    }

    public static void main(String[] args) {
    
    
    	InterruptBreakStop thread = new InterruptBreakStop();
        thread.start();
        try {
    
    
            Thread.sleep(2000);
            thread.interrupt();
       
        } catch (InterruptedException e) {
    
    
            e.printStackTrace();
        }
        System.out.println("end!");
    }
}

ここから、breakがforループから飛び出し、forループの後のコードが通常どおり実行されることがわかります。
ここに画像の説明を挿入
この問題を解決するために、returnメソッドを使用してスレッドを終了できます。

public class InterruptReturnStop extends Thread {
    
    
	 @Override
	    public void run() {
    
    
	        while (true) {
    
    
	            if (this.isInterrupted()) {
    
    
	                System.out.println("停止了!");
	                return;
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
	    }

	    public static void main(String[] args) throws InterruptedException {
    
    
	    	InterruptReturnStop thread=new InterruptReturnStop();
	        thread.start();
	        thread.sleep(2000);
	        thread.interrupt();
	    }
}

出力結果:
ここに画像の説明を挿入
スレッドストップを拡散できるように、例外をスローすることをお勧めします。

public class InterruptExceptionStop extends Thread {
    
    
	@Override
    public void run() {
    
    
	 	try {
    
    
	 		while (true) {
    
    
	            if (this.isInterrupted()) {
    
    
	                System.out.println("停止了!");
	                throw new InterruptedException();
	            }
	            System.out.println("time=" + System.currentTimeMillis());
	        }
		} catch (InterruptedException e) {
    
    
			System.out.println( "抛异常了" );
			e.printStackTrace();
		}
    }

    public static void main(String[] args){
    
    
    	InterruptExceptionStop thread=new InterruptExceptionStop();
        thread.start();
        try {
    
    
			thread.sleep(2000);
			thread.interrupt();
		} catch (InterruptedException e) {
    
    
			System.out.println( "抛异常了呀" );
			e.printStackTrace();
		}
        
    }
}

ここに画像の説明を挿入

スリープ状態のスレッドを停止するためにinterrupt()が使用される場合、catchステートメントが入力され、停止状態の値がクリアされてfalseになります。これは相互排除関係として理解できます。この割り込み方法を使用すると、スレッドをスリープ状態にすることはできません。それ以外の場合、このエラーが報告されます。

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/weixin_43888891/article/details/115291302