Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

java - JavaFX: Running a Task in a separate thread doesn't allow anything else to run

I need constant data updating in my program, so I thought that through the use of JavaFX's Task that I would be able to have it run as a separate process in my program.

final Task task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        Platform.runLater(() -> {
            while (true) {
                itemData.forEach(data -> {
                    System.out.println(data.getId());
                });
            }
        });
        return null;
    }
};
Thread thread = new Thread(task);
thread.setDaemon(true);
thread.start();

This is declared in the initialize method provided by the Initializable interface.

When running this program, however, the task is the only thing that runs, even though the task is run on a separate thread. Why would it do this and not run like intended?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're just starting a task only to use it to post a long running task on the UI thread. The Runnable

() -> {
    while (true) {
        itemData.forEach(data -> {
            System.out.println(data.getId());
        });
    }
}

still runs on the application thread, blocking it.

Only UI updates should be done on the application thread. The heavy work should be done on the other thread.

You should instead post only the updates on the application thread. Something like this:

@Override
protected Void call() throws Exception {
    while (true) {
        try {
            // add a pause between updates
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        Platform.runLater(() -> itemData.forEach(data -> {
            System.out.println(data.getId());
        }));
    }
}

If you post updates too often, this can also make the application unresponsive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...