簡體   English   中英

如何停止所有活動線程的運行

[英]How can I stop all alive threads from running

因此,我全神貫注於多線程,並編寫了一個非常基本的程序。 我的想法很簡單,我將啟動幾個線程,每個線程都將下降(遞減)到零,然后一個線程被宣布為獲勝者,而其他線程將立即停止。 我使用了一個布爾型標志,該標志終止其他線程,但有時它們會持續一會(我猜直到它們在while循環中進行檢查以查看run是否仍然為真)。

我曾嘗試過中斷,但我的理解是,這些中斷僅適用於正在睡眠,正在等待等的線程,而我使用的線程一直都在運行。 我已經使用了system.exit(1),但這也不會阻止它們,至少不會立即停止。 只是想知道更有經驗的人會做什么? 基本上,我只想讓一個線程說“好,大家現在就停止您正在做的事情”。

這是代碼:

可運行類

public class ThreadRunnable implements Runnable {

    private static boolean run;
    private int tick;

    public ThreadRunnable() {
        run = true;
        tick = 5;
    }

    public void run() {
        Thread t = Thread.currentThread();
        while (run) {
            tickDeduction();
            if (tick == 0) {
                System.out.println("Thread " + (Thread.currentThread().getId()) + " WINS");
                this.run = false;
                return;
            }
        }
    }

    public synchronized void tickDeduction() {
        System.out.println("Thread " + (Thread.currentThread().getId()) + " is at tick " + this.tick);
        this.tick--;
    }
}

主班

     public static void main(String[] args) {
        ThreadRunnable runnableBlue = new ThreadRunnable();
        ThreadRunnable runnableRed = new ThreadRunnable();
        Thread teamBlue = new Thread(runnableBlue); 
        Thread teamRed = new Thread(runnableRed);
        teamBlue.start();
        teamRed.start();
    }

基本上,我只想讓一個線程說“好,大家現在就停止您正在做的事情”。

Java應用程序無法做到這一點。 調試器也許可以做到。 (當然,JDWP協議具有凍結目標JVM中所有線程的命令...)


您在Java應用程序中獲得的最接近的結果是遍歷ThreadGroups和Threads的樹,並將不贊成使用的Thread.suspend()方法應用於每個Thread。 (請注意不要暫停當前線程...)但是suspend方法很危險(請參閱javadocs),並且不能保證您會在遍歷中看到所有線程。 當然,此(假設的)過程不是瞬時的。

使用只能聲明一次且只能聲明一次的標志。 這樣的事情就是帶有compareAndSet()方法的AtomicBoolean 要停止其他線程,您可以發送一個interrupt()

(Java曾經有權停止和殺死線程,但這會引發問題。中斷是使線程無法正常執行的唯一可靠方法。)

https://ideone.com/1F3bkH

import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    public static void main(String[] args) {
        final AtomicBoolean flag = new AtomicBoolean(false);

        final Thread[] runners = new Thread[5];

        final Random random = new Random();

        for (int i = 0 ; i < runners.length; i++){
            runners[i] = new Thread("Runner # " + i){
                @Override
                public void run() {
                    try {
                        // wait for random time
                        Thread.sleep(1000 + random.nextInt(1000));

                        // try to claim the flag
                        boolean claimed = flag.compareAndSet(false,true);

                        if(claimed){
                            System.out.println(this.getName() + " has won the race.");

                            // interrupt others
                            for (Thread t : runners){
                                if(!t.equals(this)){
                                    t.interrupt();
                                }
                            }
                        }else {
                            System.out.println(this.getName() + " has very closely lost the race.");
                        }

                    } catch (InterruptedException e) {
                        System.out.println(this.getName() + " has lost the race.");
                    }
                }
            };
        }

        // get set go
        for (int i = 0 ; i < runners.length; i++){
            runners[i].start();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM