Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Add a sleep to put the thread into idle for some interval:</p> <p><a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#sleep(long)" rel="noreferrer"><code>Thread.sleep</code></a></p> <p>Without having a sleep, the while loop will consume all the computing resources that is available. (For example, theoretically, 100% in a single core system, or 50% in a dual core, and so on.)</p> <p>For example, the following will cycle once through a <code>while</code> loop approximately every 50 milliseconds:</p> <pre><code>while (true) { try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>This should bring down the CPU utilization quite a bit.</p> <p>With a sleep in the loop, the operating system will also give enough system time for other threads and processes to do their things, so the system will be responsive as well. Back in the days of single core systems and operating systems with not-so-good schedulers, loops like this could have made the system very unresponsive.</p> <hr> <p>Since the topic of use of <code>while</code> loops for a game came up, if the game is going to involve a GUI, the game loop must be in a separate thread or else the GUI itself will become unresponsive.</p> <p>If the program is going to be a console-based game, then threading is not going to be an issue, but with graphical user interfaces which are event-driven, having a long-living loop in the code will make the GUI unresponsive.</p> <p>Threading and such are pretty tricky areas of programming, especially when getting started, so I suggest that another question be raised when it becomes necessary.</p> <p>The following is an example of a Swing application based in a <code>JFrame</code> which updates a <code>JLabel</code> that will contain the returned value from <code>System.currentTimeMillis</code>. The updating process takes place in a separate thread, and a "Stop" button will stop the update thread.</p> <p>Few concepts the example will illustrate:</p> <ul> <li>A Swing-based GUI application with a separate thread to update time -- This will prevent lock up of the GUI thread. (Called the EDT, or event dispatch thread in Swing.)</li> <li>Having the <code>while</code> loop with a loop condition that is not <code>true</code>, but substituted with a <code>boolean</code> which will determine whether to keep the loop alive.</li> <li>How <code>Thread.sleep</code> factors into an actual application.</li> </ul> <p>Please excuse me for the long example:</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TimeUpdate { public void makeGUI() { final JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); final JLabel l = new JLabel(); class UpdateThread implements Runnable { // Boolean used to keep the update loop alive. boolean running = true; public void run() { // Typically want to have a way to get out of // a loop. Setting running to false will // stop the loop. while (running) { try { l.setText("Time: " + System.currentTimeMillis()); Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } // Once the run method exits, this thread // will terminate. } } // Start a new time update thread. final UpdateThread t = new UpdateThread(); new Thread(t).start(); final JButton b = new JButton("Stop"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { t.running = false; } }); // Prepare the frame. f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(l, BorderLayout.CENTER); f.getContentPane().add(b, BorderLayout.SOUTH); f.setLocation(100, 100); f.pack(); f.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new TimeUpdate().makeGUI(); } }); } } </code></pre> <p>Some resources about threading and using Swing:</p> <ul> <li><a href="http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html" rel="noreferrer">Threads and Swing</a></li> <li><a href="http://java.sun.com/docs/books/tutorial/essential/concurrency/" rel="noreferrer">Lesson: Concurrency</a></li> </ul>
 

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