JavaFX 运行 一个线程多次

JavaFX Running a thread multiple times

我正在创建一个食品订购系统,当按下一个按钮时,它会调用一个方法,然后查询数据库以找出当前数量,然后查询另一个 table 以找出数量每道菜都需要,然后将用新数量更新数据库。这需要一两秒钟,所以我想在每次用户订购商品时在新线程上 运行 这样做,这样它就不会在每次按下按钮后挂起。我已尝试使用 executorService 执行此操作,但我仍然收到 InvocationTargetException 错误。

代码如下:

    public ExecutorService executorService = Executors.newSingleThreadExecutor();

Task<Boolean> buyDish = new Task<Boolean>() {
    @Override
    protected Boolean call() throws Exception {
       return Datasource.getInstance().insertDishSale(dishId, cost);
    }
};

public void orderFood(ActionEvent event){
    if (event.getSource() == salmon) {
        dishId = 1;
        cost = 4.99;
        executorService.execute(buyDish);
   }
}

我的问题是;

  1. 我怎样才能运行这个方法而不导致应用程序在数据库更新完成时挂起?

  2. 在不同的线程上执行此操作是否是个好主意,因为我只是在想,如果另一个线程尝试更新数据库,它将使用不是最新的数据直到所有其他线程也更新了数据库。

编辑-

Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8413)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access00(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent4(GlassViewEventHandler.java:417)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null8(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)

Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 48 more

Caused by: java.util.concurrent.RejectedExecutionException: Task com.lukedavies.controller.TestController@31bd90 rejected from java.util.concurrent.ThreadPoolExecutor@1104326[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:823)
at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1369)
at java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:668)
at com.lukedavies.controller.TestController.orderFood(TestController.java:44)

堆栈跟踪表明您在关闭执行程序服务后尝试执行任务。您通常应该只在退出应用程序时关闭执行程序服务,例如

public class MyApplication extends Application {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    @Override
    public void start(Stage primaryStage) {
        // ...
    }

    @Override
    public void stop() {
        executorService.shutdown();
    }
}

或者,如果您使用的是 FXML 和控制器:

public class MainController {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public void shutdown() {
        executorService.shutdown();
    }
}

public class MyApplication extends Application {

    private MainController mainController ;

    @Override
    public void start(Stage primaryStage) {
        FXMLLoader loader = new FXMLLoader(...);
        Parent root = loader.load();
        mainController = loader.getController();

        // ...

    }

    @Override
    public void stop() {
        mainController.shutdown();
    }
}

此外,如 documentation

中所述

As with FutureTask, a Task is a one-shot class and cannot be reused.

(顺便说一句,请注意,在不同线程上引用可变数据也是一个非常糟糕的主意。您的 dishIdcost 似乎是从 FX 引用的实例字段应用程序线程和后台线程。)

因此您不能多次使用相同的 Task。每次创建一个新的:

private ExecutorService executorService = Executors.newSingleThreadExecutor();

private Task<Boolean> createBuyDishTask(int dishId, double cost) {
    return new Task<Boolean>() {
        @Override
        protected Boolean call() throws Exception {
            return Datasource.getInstance().insertDishSale(dishId, cost);
        }
    };
}

public void orderFood(ActionEvent event){
    if (event.getSource() == salmon) {
        executorService.execute(createBuyDishTask(1, 4.99));
   }
}