添加睡眠以使线程在一段时间内处于空闲状态:
Thread.sleep
没有睡眠,while循环将消耗所有可用的计算资源。(例如,理论上,单核系统为100%,双核系统为50%,依此类推。)
例如,以下代码将
while大约每50毫秒循环一次:
while (true){ try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); }}这将大大降低CPU利用率。
有了一个休眠循环,操作系统还将为其他线程和进程提供足够的系统时间来执行其任务,因此系统也将做出响应。在单核系统和具有不太好的调度程序的操作系统的时代,像这样的循环可能会使系统反应迟钝。
由于出现了
while针对游戏使用循环的主题,因此,如果游戏要包含GUI,则游戏循环必须位于单独的线程中,否则GUI本身将无响应。
如果该程序将是一个基于控制台的游戏,那么线程就不会成为问题,而是使用事件驱动的图形用户界面,如果代码中存在长时间循环,将使GUI无响应。
线程等是编程中非常棘手的领域,尤其是在入门时,因此我建议在必要时提出另一个问题。
以下是基于的Swing应用程序的示例,该应用程序
Jframe更新
JLabel,其中将包含的返回值
System.currentTimeMillis。更新过程在单独的线程中进行,并且“停止”按钮将停止更新线程。
该示例将说明一些概念:
- 一个基于Swing的GUI应用程序,具有单独的线程来更新时间-这将防止GUI线程被锁定。(在Ewing中称为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的一些资源:
- 线程和摆动
- 课程:并发



