Java中的线程使用100%的CPU

时间:2016-12-27 13:10:42

标签: java eclipse multithreading

我用Java编写,使用Eclipse。

在我的项目(一个简单的RPG游戏)中,我有一个游戏主线程。有游戏循环,勾选和渲染等等。在Game对象中,我保留了GameState对象。

public class Game implements Runnable{

    public State gameState;
    public State menuState; // I keep one open by State.setState(gameState)

    private void tick(){
        keyManager.tick();

        getInput();

        if(State.getState() != null)
            State.getState().tick();
    }    
}

在其中,有一个World对象。

public class GameState extends State{

    private World world;

    public void tick() {
        world.tick();
    }
}

然后,我在地图上有一个每个实体的数组。

public class World {

    private EntityManager entityManager;

    public World(/*some args*/){

        for (int i=0; i<3; i++){
            addRandomNPC();

            // ^ it does some stuff, but in the end, it uses:
            // entityManager.addEntity(new NPC(/*random args*/));
        }

    }

    public void tick(){
        entityManager.tick();
    }

}

public class EntityManager{

    private ArrayList<Entity> entities;

    public void tick(){
        for(int i = 0;i < entities.size();i++){
            Entity e = entities.get(i);
            e.tick();
        }
        entities.sort(renderSorter);
    }
}

我添加一个NPC。我想让它继续前进(随机时间随机移动一段时间),所以我在它们内部创建了一个线程。更具体地说,我有一个AutoMover类,它实现了Runnable。

public class NPC extends Creature {

    private Automover autoMover;

    public void tick(){
        randomizeInput();
        move();
    }

    private randomizeInput() {
        xMove = autoMover.getxMove();
        yMove = autoMover.getyMove();
    }
}

public class AutoMover implements Runnable {

    private Timer timer

    public void run() {
        timer = new Timer();
        Random gen = new Random();
        duration = gen.nextFloat()*Utils.maxAutoMoverDuration;

        while(running){
            timer.update();


            if(timer.timer >= duration*1000000000){ 

                // some simple math about xMove, yMove and duration

            duration = gen.nextFloat()*Utils.maxAutoMoverDuration;
            timer.timer = 0;
        }
    }

    stop(); // does some extra stuff when closing the thread

}

所以...我试图添加1个NPC。工作。 2 - 工作。 10 - 该死的!就好像我的CPU开始对我大喊大叫。有可能,10个NPC的所有这些线程都使用了这么多CPU吗?什么是更好的方法呢?我想让它真正随机和独立。

2 个答案:

答案 0 :(得分:3)

100%通常表示您没有“睡眠”您的线程。我也没有在你的代码中发现任何迹象。

所以,那就是:可以预期。答案很简单:让你的线程保持“热”循环;除了检查循环条件之外什么都不做。你看,现代CPU可以做到这一点(检查循环条件)每秒许多次。而且它发现这么无聊会让人感到愤怒,也就是说它很热。

一个简单的Thread.sleep(50),或100,或xxx应该在这里做!

答案 1 :(得分:1)

它与eclipse无关这里是一个代码的例子,它也会使用很多CPU虽然它没有做任何特别的事情

public static void main(String[] args) {
    Thread t = new Thread(() -> {
        while (true) {
            System.out.println("Printing stuff");
        /*  try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
        }
    });

    t.start();
}

在此代码中,每次迭代之间没有暂停,因此CPU几乎从不重新编号。如果您取消注释它,请注释注释部分突然CPU不会以相同的速率使用。

相关问题