添加一个睡眠以使线程空闲一段时间:
没有睡眠,while循环将消耗所有可用的计算资源。 (例如,理论上,单核系统中为100%,双核中为50%,依此类推。)
例如,以下内容将大约每50毫秒循环一次while循环:
while (true)
{
try
{
Thread.sleep(50);
}
catch (Exception e)
{
e.printStackTrace();
}
}
这应该会降低CPU的利用率。
在循环中休眠时,操作系统还将为其他线程和进程提供足够的系统时间来执行其操作,因此系统也将响应。 在具有不太好的调度程序的单核系统和操作系统的时代,像这样的循环可能使系统非常无响应。
由于游戏使用while循环的主题出现了,如果游戏涉及GUI,游戏循环必须在一个单独的线程中,否则GUI本身将变得无响应。
如果该程序将成为基于控制台的游戏,那么线程不会成为问题,但是对于事件驱动的图形用户界面,在代码中具有长期循环将使GUI无响应。
线程等等都是非常棘手的编程领域,特别是在入门时,所以我建议在必要时提出另一个问题。
以下是基于JFrame的Swing应用程序示例,该应用程序更新将包含System.currentTimeMillis返回值的JLabel 。 更新过程在一个单独的线程中进行,“停止”按钮将停止更新线程。
该示例的几个概念将说明:
基于Swing的GUI应用程序,具有单独的线程来更新时间 - 这将防止GUI线程的锁定。 (在Swing中称为EDT或事件派发线程。)
使while循环的循环条件不为true ,但用boolean替换,它将决定是否保持循环活动。
Thread.sleep如何影响实际应用程序。
请原谅我的长期例子:
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();
}
});
}
}
有关线程和使用Swing的一些资源: