Как управлять всеми активными потоками в приложении JavaFX

#java #multithreading #javafx #thread-priority

#java #многопоточность #javafx #приоритет потока

Вопрос:

System.out.println(Thread.activeCount()); выводит количество активных потоков.

Как только я запускаю свое приложение, оно сообщает, что оно запускает 6 потоков. Как можно было бы управлять (скажем, приоритетом) всеми этими потоками?

Ввод System.out.println(Thread.currentThread().getName()) моего кода всегда печатается JavaFX Application Thread .

Ответ №1:

Вы можете использовать enumerate метод Thread класса. Это позволит вам получить все потоки группы потоков и скопировать их в массив.

Рабочий пример

 import javafx.application.Application;
import javafx.stage.Stage;

public class ThreadDemo extends Application {

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

    @Override
    public void start(Stage stage) throws Exception {
        int count = Thread.activeCount();
        System.out.println("currently active threads = "   count);

        Thread th[] = new Thread[count];
        // returns the number of threads put into the array
        Thread.enumerate(th);

        // set the priority
        for (int i = 0; i < count; i  ) {
            // Priority 0 is not allowed
            th[i].setPriority(i   1);
            System.out.println(i   ": "   th[i]   " has priority of "
                      th[i].getPriority());
        }

        // To check if change in priority is reflected
        System.out.println("Current Thread "   Thread.currentThread().getName()
                  " priority "   Thread.currentThread().getPriority());
    }
}