代码之家  ›  专栏  ›  技术社区  ›  Aly

从EDT使线程在非EDT(事件调度线程)线程上运行

  •  4
  • Aly  · 技术社区  · 16 年前

    我有一个在EDT上运行的方法,我想让它在一个新的(非EDT)线程上执行一些东西。我目前的代码如下:

    @Override
        public void actionPerformed(ActionEvent arg0) {
    //gathering parameters from GUI
    
    //below code I want to run in new Thread and then kill this thread/(close the JFrame)
    new GameInitializer(userName, player, Constants.BLIND_STRUCTURE_FILES.get(blindStructure), handState);
    }
    
    2 回复  |  直到 10 年前
        1
  •  3
  •   Amir Afghani    16 年前

    @Override
        public void actionPerformed(ActionEvent arg0) {
    
            Thread t = new Thread("my non EDT thread") {
                public void run() {
                    //my work
                    new GameInitializer(userName, player, Constants.BLIND_STRUCTURE_FILES.get(blindStructure), handState);
                }
    
            };
            t.start();
        }
    
        2
  •  8
  •   smalltown2k    16 年前

    你可以用 SwingWorker 在EDT之外的工作线程上执行任务。

    例如。

    class BackgroundTask extends SwingWorker<String, Object> {
        @Override
        public String doInBackground() {
            return someTimeConsumingMethod();
        }
    
        @Override
        protected void done() {
            System.out.println("Done");
        }
    }
    

    不管你叫它什么:

    (new BackgroundTask()).execute();