File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Making main thread wait for an action in swing components using while loop.

 
Mohamed Iqzas
Ranch Hand
Posts: 72
Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am reading one text file by comparing each line with a specific string and printing them in console.

I am also getting one input, i am waiting for a JFrame to be closed before printing all the lines.

I'm using a window listener to update a boolean flag when the JFrame is closed. Until that flag is updated to true i am looping using while indefinitely in main method.

Once the execution is out of the while loop, after the JFrame operation has updated the boolean variable, the rest of the code is not acting the same way as expected.

Is this due to some synchronisation issue. ? I am not using any input from the JFrame for now, because i just wanted to test if this works fine before using it.

Please find the code below:



Here if I comment out the code between Swing START and Swing END, then the program works just fine, all the text i wanted from inputText file gets printed in console. Now If make the main method wait using that while loop, its getting bad. Though here I'm not using any input from that JList for reading the file, I might use it later.

I can feel that its somewhat a bad logic to use that boolean flag, but whats wrong here?

Thanks.
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will have to be more specific about what the problem is. What is going wrong? What does 'it's getting bad' mean? What is different between what you expect and what happens?

Having the while loop like that is probably not a good idea. You could make the application consume a lot of CPU time doing nothing. The first concern is that the selected variable should be volatile so it can be properly synchronized between threads. Second, you should add some sleep time in the loop to free up some CPU time (because it is nice). Finally, you should probably do something even better than a tight loop like that. Instead use synchronized blocks with wait() on the main thread and notify() in the GUI thread. This is a more friendly (less CPU intensive way) of signaling between threads. There are also other alternatives which may be more appropriate or make waiting for the GUI to finish easier - things like Semaphore, or CountDownLatch, or because you will eventually be sending data from the GUI to the main thread, a SynchronousQueue (these last 3 suggestions are in the java.util.concurrent package).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic