如何使用线程暂停java中的执行

我以编程方式创建了一个向导。 它包含3个面板。 第二个是devicePane,第三个是detailsPane。 第三个面板由进度条组成。 我希望我的程序在显示第三个面板后启动一个函数process() ? 是否可以使用线程?

 else if(ParserMainDlg.this.POSITION==1){ if(sqlConnectionPane.executeProcess()==true){ devicePane.setDeviceList(); ParserMainDlg.this.POSITION++; fireStateChanged(oldValue); } } else if(ParserMainDlg.this.POSITION==2){ System.out.println("position:"+ParserMainDlg.this.POSITION); if(devicePane.executeProcess()==true){ ParserMainDlg.this.POSITION++; fireStateChanged(oldValue); } 

我希望sqlConnectionPane.executeProcess()调用一个在显示devicePane面板后开始执行的函数?

您可以明确地使用线程来执行任务,这是处理长时间运行任务的首选方法。

你有多种选择。 所有选项都包括向您的向导进行回调,以更新进度条。

您可以创建自己的任务类,也可以使用现有的SwingWorker 。 “SwingWorker本身是一个抽象类;您必须定义一个子类才能创建SwingWorker对象;匿名内部类通常用于创建非常简单的SwingWorker对象。”

使用我们刚刚了解到的swing工作者可以使用以下内容:

 SwingWorker backgroundWork = new SwingWorker() { @Override protected final Integer doInBackground() throws Exception { for (int i = 0; i < 61; i++) { Thread.sleep(1000); this.publish(i); } return 60; } @Override protected final void process(final List chunks) { progressBar.setValue(chunks.get(0)); } }; backgroundWork.execute(); 

请注意,您必须将任务分解为更小的部分才能实际显示进度。