JavaFX多次运行一个线程

时间:2017-09-13 17:53:58

标签: java multithreading javafx executorservice

我正在创建一个食物订购系统,当按下按钮时,它将调用一个方法,然后查询数据库以找出当前数量,然后查询另一个表以找出每个菜肴所需的数量,以及然后将使用新数量更新数据库。这需要一两秒钟,所以我想在每次用户订购项目时在新线程上运行它,这样每次按下按钮后它都不会挂起。我尝试使用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. 在不同的线程上执行此操作是个好主意,因为我只是想如果另一个线程试图更新数据库,那么它将处理所有其他线程之前不是最新的数据已经更新了数据库。

  3. 编辑 -

    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$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.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.access$1500(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$handleMouseEvent$354(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$null$148(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$1@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)
    

1 个答案:

答案 0 :(得分:2)

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

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

中所述
  

与FutureTask一样,Task是一次性类,不能重复使用。

(另外,请注意,在不同的线程上引用可变数据也是一个非常糟糕的主意。您的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));
   }
}