Java wait for JFrame to finish

前端 未结 2 1123
夕颜
夕颜 2020-12-19 20:27

I have a login frame that i have to wait for from another thread. Upon successful login frame disposes itself. And i want to pop up the main frame for the application. Right

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 20:45

    If you have Java 5 or later available, you could use a CountDownLatch. For example, assuming the main frame is in control initially, have the main frame create the CountDownLatch with a count down of 1 and pass this latch to the login frame. Then have the main frame wait for the latch to become 0:

    CountDownLatch loginSignal = new CountDownLatch(1);
         ...    // Initialize login frame, giving it loginSignal 
         ...    // execute login frame in another Thread
    // This await() will block until we are logged in:
    loginSignal.await();
    

    Have the login frame, when done, decrement the Latch:

    loginSignal.countDown();
    

    Ensure that there is no way for your login frame to exit where it forgets to decrement the latch! As soon as the CountDownLatch reaches 0, the main frame becomes runnable.

    You could also use a Semaphore or Condition (or any of a few other choices from java.util.concurrent), but for this purpose, a CountDownLatch seems easier to use.

提交回复
热议问题