java如何中断while,如何停止Java while循环占用超过50%的CPU?

本文讨论了如何通过在while循环中添加Thread.sleep()来减少CPU使用率,从而避免程序占用过高资源。作者提供了示例代码,展示了一个在Swing应用中更新时间的后台线程,同时保持GUI响应性。此外,还强调了在图形用户界面中使用长循环可能带来的问题以及解决策略。
摘要由CSDN通过智能技术生成

Okay, I tested this on an empty program, and just having a while(true){} running gave me >50% on my CPU. I have a game I'm working on that uses a while loop as it's main loop, and it's CPU is at 100 all the time.

How can I get Java to repeat something over and over without eating up >50% of my CPU just to do the repeating?

解决方案

Add a sleep to put the thread into idle for some interval:

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.)

For example, the following will cycle once through a while loop approximately every 50 milliseconds:

while (true)

{

try

{

Thread.sleep(50);

}

catch (Exception e)

{

e.printStackTrace();

}

}

This should bring down the CPU utilization quite a bit.

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.

Since the topic of use of while 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.

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.

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.

The following is an example of a Swing application based in a JFrame which updates a JLabel that will contain the returned value from System.currentTimeMillis. The updating process takes place in a separate thread, and a "Stop" button will stop the update thread.

Few concepts the example will illustrate:

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.)

Having the while loop with a loop condition that is not true, but substituted with a boolean which will determine whether to keep the loop alive.

How Thread.sleep factors into an actual application.

Please excuse me for the long example:

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();

}

});

}

}

Some resources about threading and using Swing:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值