Wait until end of thread execution before executing the next method

后端 未结 6 2076
慢半拍i
慢半拍i 2021-01-28 19:28

I\'ve a JFrame subclass that manage my UI and call a method of Item Object to import items in my DB:

public TestGUI() throws IOException
{

    initComponents();         


        
6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-28 20:00

    If you want one Thread to wait for another, you can always use a CountDownLatch also. Using one also means that you do not have to wait until some threads finishes completely. If you would make your question better understandable for us, we could help with more details.

    You need to share a CountDownLatch for example between the Threads:

    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
    }
    

    And on the other side:

    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
        }
    
    
    }
    

提交回复
热议问题