繁体   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