等到执行下一个方法之前执行线程结束

我有一个JFrame子类来管理我的UI并调用Item Object的方法来导入我的数据库中的项目:

public TestGUI() throws IOException { initComponents(); Item.importItems(progressBar); // static method that execute a new thread to import item witouth freeze my UI (I update a progressBar in it) table.refresh(); //Metodh that I need to execute only after "importItems()" methods is completed } 

Item对象实现Runnable以在新Thread中执行导入操作

 public Item implements Runnable { private JProgressBar progressBar; public void importItems (JProgressBar progressBar) throws IOException //Metodo per importare articoli da un file esterno. Usa i Thread. { this.progressBar = progressBar; Thread importThread = new Thread (new RefreshTable(),"Importer Thread"); importThread.start(); } void run () { // I execute here all the DB operation that i need. I also update the progress bar here } } 

只有在Item.importImtes(progressBar)结束执行后,如何修改该代码才能执行table.refresh() ? 谢谢!

如果您希望一个Thread等待另一个,您也可以始终使用CountDownLatch 。 使用一个也意味着您不必等到某些线程完全完成。 如果您希望我们能够更好地理解您的问题,我们可以提供更多详细信息。

您需要在Threads之间共享一个CountDownLatch:

 public TestGUI() throws IOException{ initComponents(); private final CountDownLatch latch = new CountDownLatch(1); Item.importItems(progressBar, latch); // static method that execute a new thread to import item witouth freeze my UI (I update a progressBar in it) latch.await(); table.refresh(); //Metodh that I need to execute only after "importItems()" methods is completed } 

另一方面:

 public Item implements Runnable { private JProgressBar progressBar; public void importItems (JProgressBar progressBar, CountDownLatch latch) throws IOException { //Metodo per importare articoli da un file esterno. Usa i Thread. this.progressBar = progressBar; Thread importThread = new Thread (new RefreshTable(),"Importer Thread"); importThread.start(); } void run () { // I execute here all the DB operation that i need. I also update the progress bar here //After everything finishes: latch.countDown(); // you want this to be executed in a finally block of the try catch } } 

在线程上使用.join()方法。

如果您使用Swing请查看SwingWorker和SwingUtilities 。
它们包含辅助线程API

.join()方法将阻塞当前线程,直到完成。

这是你应该如何使用它:

 class ProgressBar extends Thread{ public void run(){ System.out.println("Progress Bar - start"); try { Thread.currentThread().sleep(2000); } catch (InterruptedException e) {} System.out.println("Progress Bar - end"); } } public class ThreadDemo { public static void main(String[] args) throws InterruptedException { System.out.println("Main Thread Start"); Thread t1 = new Thread(new ProgressBar()); t1.start(); t1.join(); System.out.println("Main Thread End"); } } 

OUTPUT:

 Main Thread Start Progress Bar - start Progress Bar - end Main Thread End 

你可以做的是移动table.refresh(); 子线程代码末尾的代码,并使用SwingUtilities.InvokeLater将其转发到GUI线程事件队列:

  public void run() { //... SwingUtilities.InvokeLater( new Runnable() { public void run() { table.refresh(); } }); } 

这样你就可以在GUI线程上执行它,但只有当子线程完成它的工作时才会执行它。