Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you're using swing, you're already using threads. Swing by its nature has a thread for I/O and a thread for back-end. You do indeed want to use threads here - among other things, putting a thread in wait is a lot cheaper than giving it an infinite loop to churn on. </p> <p>Listeners are another application of threads, and I wouldn't be surprised if you could get most or all of what you want just by using well-constructed listeners. Alternately, there are these things called semaphores. Semaphores are a way for threads to handle timing - if a thread attempts to lock a semaphore that's already locked, it will wait until another thread unlocks it before continuing (and locking it again). In your case, you might try the following.</p> <ul> <li>Have a button listener, a main function, and a locked semaphore.</li> <li>Main function starts, does any initial behaviors, and attempts to grab semaphore. since the semaphore is already locked, it holds.</li> <li>When the button listener fires, one of the things it does is unlock the semaphore.</li> <li>As soon as the semaphore unlocks, the main function grabs it (thus locking it once more) and does whatever it's supposed to do. Eventually, it finishes that, and attempts to grab the (locked) semaphore again, thus waiting for the next time the button listener fires.</li> <li>repeat.</li> </ul> <p>Edit: To include and explain the actual accepted solution (from comments below).</p> <p>Fix: add <code>Thread.sleep(1000);</code> to the inside of the while loop in the whileConnected function.</p> <p>Explanation: The while loop is an infinite loop that contains nothing but an if statement. This if statement evaluates to false (and therefore does nothing further) for a really long time (at least as far as the computer is concerned). This acts in much the same way an electrical short does - there's nothing to slow it down, so the thread that runs that main function burns up a lot of computing resources doing nothing. This is bad. It is possible that some failsafe kicked in and killed the thread. It is possible that the thread failed or broke something in an uglier manner. In any case, including a sleep statement (in this case, sleeping for a second each loop, as it's measured in ms) prevents this, and thus allows the function to continue indefinitely.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload