Search code examples
javamultithreadingjavafxthread-priority

How to manipulate all active threads in a JavaFX application


System.out.println(Thread.activeCount()); prints the number of active threads.

Right as I start my application, it says it is running 6 threads. How would one go about to manipulate (say, priority of) all these threads?

Putting System.out.println(Thread.currentThread().getName()) in my code always prints JavaFX Application Thread.


Solution

  • You can use enumerate method of Thread class. This will allow you to get all the threads of a thread group and copy them to an array.

    A working example

    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());
        }
    }