【问题标题】:JAVAFX Concurency with querying the DB [duplicate]查询数据库的JAVAFX并发[重复]
【发布时间】:2014-07-01 14:41:50
【问题描述】:

我正在使用 JAVAFX over JAVA8 构建一个应用程序。 在我的应用程序中,我有一个数据网格,应该填充来自数据库的结果集。 但是,查询可能需要一段时间,我不希望 GUI 在那之前处于空闲状态。

解决这类问题的最佳线程架构是什么?

我考虑过为查询本身使用任务,而不是将结果放入数据网格中。 但是,主 UI 线程不允许其他线程接触对象。 如果我只是等待线程结束,它就会变成一个同步过程(我想避免)

有什么想法吗?

【问题讨论】:

    标签: java multithreading


    【解决方案1】:

    我会去完成那个任务。在后台进行长时间运行的操作总是一个好主意,这样 UI 就不会冻结。此外,您可以考虑分页(例如,通过在表格中向下滚动,或上一个和下一个按钮)

    这是我使用任务的方法

        final Task<List<User>> searchUserTask = new Task<List<User>>() {
            @Override
            protected List<User> call() throws Exception {
                  //search logic, for example call to DB
                  return //list of users
            }
    
        };
    
        //Here we add a listener to the state, so that we can know when the operation finishes, and decide what to do after
        searchUserTask.stateProperty().addListener((ObservableValue<? extends Worker.State> source, Worker.State oldState, Worker.State newState) -> {
    
            if (newState.equals(Worker.State.SUCCEEDED)) { //the operation finished successfully
                List<User> result = searchTask.getValue();
                //set value to a UI component (this method runs on the UI thread)
                //usersTable.getItems().setAll(matches);
            } else if (newState.equals(Worker.State.FAILED)) {
                Throwable exception = searchTask.getException();
                log.error("Contact search failed", exception);
            }
        });
    
        new Thread(searchUserTask).start();
    

    所以在这里你有一种模拟回调机制的方法。 您向状态添加一个侦听器,当它发生变化时,事件将自动触发,并由您来正确捕获它,然后处理成功状态等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 2017-09-22
      • 2019-06-10
      • 2017-03-01
      相关资源
      最近更新 更多