java - 试图阻止Java中同时运行的单个线程

标签 java multithreading javafx textfield java-threads

因此,当我运行多个线程时,我试图停止单个线程,这是我用来初始化线程的代码。基本上,我在 javafx 中有多个文本字段,当单击屏幕上的按钮时,它会用递增的计时器一个接一个地填充文本字段。现在我还有一个用于每个文本字段的按钮来清除它,但问题是当我清除它时,因为线程仍在运行,计时器消失了一秒钟,然后由于行 'orderTimes.get(boxNo ).setText(分+秒);'在代码中。

现在我尝试的是创建一个线程列表,我尝试在下面实现它,但它不起作用,这样如果单击了清除按钮,我就可以调用每个单独的线程。

有谁知道如何仅关闭/停止正在运行的多个线程中的一个线程?如果需要更多信息,请告诉我,谢谢。

public static void createIncrementingTimer(int boxNo, List<TextField> orderTimes) {
minutesList.set(boxNo, 0);
secondsList.set(boxNo, 0);
state = true;
new Thread(threadList.get(boxNo))  {
  int currentMinutes = 0;
  int currentSeconds = 0;
  public void run() {
    for (;;) {
      if (state = true) {
        try {
          sleep(1000);
          if (secondsList.get(boxNo) > 59) {
            secondsList.set(boxNo, 0);
            currentSeconds = 0;
            minutesList.set(boxNo, currentMinutes + 1);
            currentMinutes++;
          }            
          if (secondsList.get(boxNo) < 10) {
            second = ":0" + Integer.toString(secondsList.get(boxNo));
          } else {
            second = ":" + Integer.toString(secondsList.get(boxNo));                 
          }                            
          secondsList.set(boxNo, currentSeconds + 1);
          currentSeconds++;            
          if (minutesList.get(boxNo) < 10) {
            minute = "0" + Integer.toString(minutesList.get(boxNo));
          } else {
            minute = Integer.toString(minutesList.get(boxNo));
          }
          orderTimes.get(boxNo).setText(minute + second);             
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
  }
};
threadList.get(boxNo).start();
}

我用来清除文本字段的代码如下,其中 orderTimes 是我尝试清除的文本字段的列表。

public static void eraseBox(int clickedButtonNumber, List<TextArea> orderContentsList, List<TextField> tableNumbers, List<TextField> orderNumbers, List<TextField> orderTimes) {
orderContentsList.get(clickedButtonNumber).setText(null);
  tableNumbers.get(clickedButtonNumber).clear();
  orderNumbers.get(clickedButtonNumber).clear();
  orderTimes.get(clickedButtonNumber).clear();
}

最佳答案

我建议您尽量避免线程Animation API 旨在使通常在 Thread 中完成的工作变得更容易。在此示例中,IncrementingTimer 类由两个Labels 和三个Buttons 组成。 Labels 用于显示时间。 按钮用于控制时间轴Timeline 用于每秒或每 60 秒递增 Labels 值。我已向应用程序添加了三个 IncrementingTimers

主要

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * JavaFX App
 */
public class App extends Application {

    @Override
    public void start(Stage stage) {        
        var scene = new Scene(new VBox(new IncrementingTimer(), new IncrementingTimer(), new IncrementingTimer()), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

递增计时器

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.util.Duration;

/**
 *
 * @author blj0011
 */
final public class IncrementingTimer extends HBox
{
    IntegerProperty secondsCounter = new SimpleIntegerProperty();//Keeps up with seconds
    IntegerProperty minutesCounter = new SimpleIntegerProperty();//Keeps up with minutes

    Label lblSeconds = new Label();//Displays the seconds
    Label lblMinutes = new Label();//Displays the minutes
    Label lblColon = new Label(":");//Display the colon between minutes and seconds

    Button btnPlay = new Button("Play");//Plays the Timeline
    Button btnStop = new Button("Stop");//Stops the Timeline
    Button btnPause = new Button("Pause");//Pauses the Timeline

    Timeline timeline;//Used to run code that changes the Labels. This Timeline runs every one second.

    public IncrementingTimer()
    {
        lblSeconds.textProperty().bind(secondsCounter.asString("%02d"));//Binds the seconds label to the seconds counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.
        lblMinutes.textProperty().bind(minutesCounter.asString("%02d"));//Binds the minutes label to the minutes counter. Sets the String to always show two digits. Exmaple 1 is shown as 01.

        getChildren().addAll(lblMinutes, lblColon, lblSeconds, btnPlay, btnStop, btnPause);

        timeline = new Timeline(new KeyFrame(Duration.seconds(1), (event) -> {//Replace the one with .016 to speed this up for testing purposes.
            secondsCounter.set(secondsCounter.get() + 1);
            if (secondsCounter.get() == 60) {
                secondsCounter.set(0);
                minutesCounter.set(minutesCounter.get() + 1);
                if (minutesCounter.get() == 60) {
                    minutesCounter.set(0);
                }
            }
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);
        btnPlay.setOnAction((event) -> {
            timeline.play();
        });
        btnPause.setOnAction((event) -> {
            timeline.pause();
        });
        btnStop.setOnAction((event) -> {
            timeline.stop();
            secondsCounter.set(0);
            minutesCounter.set(0);
        });

        this.setAlignment(Pos.CENTER);
    }

}

关于java - 试图阻止Java中同时运行的单个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60226658/

相关文章:

java - 返回类型中的推断通配符泛型

java - 如何在java中打印一个Arraylist中的单词以及另一个Arraylist中的单词

java - 如何远程连接到 unix 机器并启动/关闭服务器?

javafx 可点击图像 map

java - 如何在另一个方法中使用同一个类中的方法,这需要不同的参数

java - android和javafx轻量级兼容事件框架

Java jar 输出。它去哪儿了?

java - 检查对象的过期日期以在后台删除

javascript - Node Js 内部线程池究竟是如何工作的?

Java 监听线程状态