Java - 终止Thread中的方法

Cod*_*Guy 7 java multithreading

我有一个Java带有run方法的线程来计算很多东西.您可以将其视为一系列数学语句,如下所示.注意,每个计算可以使用其他方法,这些方法又可以具有额外的循环等.

public void run() {
   [computation 1 goes here here that takes a few seconds]
   [computation 2 goes here that takes a few seconds]
   ....
   [computation 30 goes here that takes a few seconds]
}
Run Code Online (Sandbox Code Playgroud)

有一个GUI打印这些语句的输出,因为它们产生了结果,我希望用户能够随时说"停止".这是我想到的两种方法


方法1:许多布尔检查[LOOKS TERRIBLE]

private boolean stop;
public void run() {
   if(!stop)
       [computation 1 goes here here that takes a few seconds]
   if(!stop)
       [computation 2 goes here that takes a few seconds]
   ....
   if(!stop)
       [computation 30 goes here that takes a few seconds]
}
Run Code Online (Sandbox Code Playgroud)

在此方法中,一旦将停止标志设置为true,计算将结束.注意这看起来多么愚蠢,有30个if陈述.重要的是,这里的关键问题是如何经常提出这些条件.请注意,每行上的计算不一定是单行.采取极端的run()方法,该方法中的每一行都值得if(!stop)在它上面进行调用吗?这似乎不是很好的设计.

方法2:推广计算[不能这样做]

pirivate boolean stop;
public void run() {
   for(int i = 0; i < computationsN && !stop; i++) {
       computuations.get(i).compute();
}
Run Code Online (Sandbox Code Playgroud)

我想,这个方法会被提出,所以我想简单地指出,这是在我的情况是不可能的,因为在我打电话"计算"的简单线条的纯粹变化.我通常对基本while循环的线程执行此操作,并且它适用于此类.但是在这种情况下,当run()方法只是一个巨大的变量代码方法时.


还有其他解决方案吗?这似乎应该是一个普遍的问题.提前致谢!

Jor*_*cio 5

你想要做的事情实际上可以通过方法2完成,但你必须使用策略模式,这是你需要的另一件事,因为它可以简化你的计算在一行中,就像你实际做的那样方法2.

它的工作方式如下,它允许您通过执行多态来更改下一个可执行算法.

在此输入图像描述

首先,您必须在不同的类中创建所有算法,并且每个算法必须Computable使用一个方法(即您的compute()方法)实现一个接口(可以调用它).

防爆.

public interface Computable {
    public void compute();
}
Run Code Online (Sandbox Code Playgroud)

你的算法类可能是这样的:

  public class AlgorithmX implements Computable {

    @Override
    public void compute() {
        // TODO Your Real Computation here for the Algorithm X
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后在你的for循环中你的computations集合(或数组)填充了实现的对象Computable,即使用你的算法对象.

for(int i = 0; i < computations && !stop; i++) {
   computuations.get(i).compute();
}
Run Code Online (Sandbox Code Playgroud)

因此,您正在使用方法2走上正确的道路,我希望您的方式现在更清晰.

干杯!