Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在给定时间过后停止线程中的算法_Java_Multithreading - Fatal编程技术网

Java 在给定时间过后停止线程中的算法

Java 在给定时间过后停止线程中的算法,java,multithreading,Java,Multithreading,假设我有一个算法,对给定的参数做一些事情。如果该算法运行时间超过100毫秒,则我希望停止该算法并重试其他参数 我在下面发布了测试随机参数算法的代码。。。我认为代码可能是这样的: public class StopThread { private Lock lock = new ReentrantLock(); public static void main(String... args) { System.out.println("Starting thread

假设我有一个算法,对给定的参数做一些事情。如果该算法运行时间超过100毫秒,则我希望停止该算法并重试其他参数

我在下面发布了测试随机参数算法的代码。。。我认为代码可能是这样的:

public class StopThread {
    private Lock lock = new ReentrantLock();

    public static void main(String... args) {
        System.out.println("Starting threads...");
        (new StopThread()).startThreads(100);
    }

    private void startThreads(int nrOfThreads) {
        for (int i = 0; i < nrOfThreads; i++) {
            startThread(i, (long) (Math.random() * 10000000000l));
            System.out.println("Started thread number " + (i + 1));
        }
    }

    private void startThread(final int number, final long load) {
        Thread workerThread = new Thread() {
            @Override
            public void run() {
                try {
                    lock.lock();
                    doAlgorithmWork(load);
                } finally {
                    System.out.println("Thread " + (number + 1) + " finished...");
                    lock.unlock();
                }
            }
        };
        Thread timerThread = new Thread() {
            @Override
            public void run() {
                try {
                    sleep(100);
                } catch (InterruptedException e) {
                }
            }
        };

        workerThread.start();
        timerThread.start();

        do {
            if (!workerThread.isAlive() || !timerThread.isAlive()) {
                workerThread.stop();
                timerThread.stop();
            }
        } while (!workerThread.isAlive() && !timerThread.isAlive());
    }

    protected void doAlgorithmWork(long load) {
        while (load-- > 0) {
        }
    }
}

我觉得这个问题应该已经有了答案,但我发现到现在为止似乎很复杂,我不知道如何使用它。我对线程不是很了解,如果您能发布一些代码,我将不胜感激

一个非常简单的解决方案如下所示:

private void startThreads(int nrOfThreads) {
    for (int i = 0; i < nrOfThreads; i++) {
        Thread worker = new Thread() {
            @Override
            public void run() {
                doAlgorithmWork((long) (Math.random() * 10000000000l));
            }
        }
        worker.start();
        worker.join(100); //block until either the thread is done, or 100ms passed
        if (worker.isAlive()) worker.stop(); //if thread is still alive, stop it
    }
}
public class Worker implements Runnable {
    private volatile boolean stopped = false;

    public void stop() {
        stopped = true;
    }

    @Override
    public void run() {
        doAlgorithmWork((long) (Math.random() * 10000000000l));
    }

    private void doAlgorithmWork(long load) {
        while (!stopped && load-- > 0) {
            //calculation
        }
    }
}
private void startThreads(int nrOfThreads) {
    for (int i = 0; i < nrOfThreads; i++) {
        Thread worker = new Thread(new Worker());
        worker.start();
        worker.join(100); //block until either the thread is done, or 100ms passed
        if (worker.isAlive()) worker.stop(); //if thread is still alive, stop it
    }
}
然后你的跑步者看起来像这样:

private void startThreads(int nrOfThreads) {
    for (int i = 0; i < nrOfThreads; i++) {
        Thread worker = new Thread() {
            @Override
            public void run() {
                doAlgorithmWork((long) (Math.random() * 10000000000l));
            }
        }
        worker.start();
        worker.join(100); //block until either the thread is done, or 100ms passed
        if (worker.isAlive()) worker.stop(); //if thread is still alive, stop it
    }
}
public class Worker implements Runnable {
    private volatile boolean stopped = false;

    public void stop() {
        stopped = true;
    }

    @Override
    public void run() {
        doAlgorithmWork((long) (Math.random() * 10000000000l));
    }

    private void doAlgorithmWork(long load) {
        while (!stopped && load-- > 0) {
            //calculation
        }
    }
}
private void startThreads(int nrOfThreads) {
    for (int i = 0; i < nrOfThreads; i++) {
        Thread worker = new Thread(new Worker());
        worker.start();
        worker.join(100); //block until either the thread is done, or 100ms passed
        if (worker.isAlive()) worker.stop(); //if thread is still alive, stop it
    }
}
您还可以为Worker创建一个构造函数,它接受负载值,而不是在Worker内部生成负载值


请注意,如果doAlgorithm中的计算太耗时,线程可能会运行100毫秒以上,因为它总是在循环中完成每个计算。如果这是一个问题,那么您的替代方法是中断线程而不是调用worker。中断将导致在run方法中抛出InterruptedException。

可能有用:@Daniel我查看了答案,但从我尝试的结果来看,它没有按预期工作。实际上,我想对线程进行排队,并且不要在并行或多线程上运行它们,因为这是算法的基准。谢谢你的重播,我希望它能正常工作。缺点就像您提到的使用不推荐的Thread.stop.Further注释:我不想更改doAlgorithmWork方法,因为我并不总是能够访问它。因此,第一种方法似乎仍然是可以选择的。然而,即使它有效,我觉得我不应该相信线程。停止。它的行为很奇怪。例如,在调用Thread.stop之后,finally块有时执行,有时不执行。即使线程完成了执行,程序似乎也不会终止……如果不修改doAlgorithmWork,就无法很好地处理这个问题。您可以尝试使用“Thread.interrupt”查看详细信息,但这可能仍然不够。