Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java for循环中的Sleep()_Java_Multithreading_Algorithm_Sleep - Fatal编程技术网

Java for循环中的Sleep()

Java for循环中的Sleep(),java,multithreading,algorithm,sleep,Java,Multithreading,Algorithm,Sleep,所以我写了一个兔子和狼的模拟,我有一个线程,在它的运行中对所有动物在for循环中进行迭代——一个用于兔子,一个用于狼。因此: public void run(){ while(rabbitNumber!=0){ for(int i=0; i<rabbitsNumber; i++){ doRabbitMove();} for(int i=0; i<wolvesNumber; i++){ doWofMove();}

所以我写了一个兔子和狼的模拟,我有一个线程,在它的运行中对所有动物在for循环中进行迭代——一个用于兔子,一个用于狼。因此:

public void run(){
    while(rabbitNumber!=0){
                for(int i=0; i<rabbitsNumber; i++){ doRabbitMove();}
                for(int i=0; i<wolvesNumber; i++){ doWofMove();}
            }
    }
public void run(){
while(位号!=0){

对于(inti=0;i我不完全清楚您的需求,但是您可以只使用几个线程,甚至只需要一个额外的线程

我将把处理要求(所有动物都必须移动)设置到一个线程中,并在一个单独的线程中处理队列

DelayQueue-延迟元素的无界阻塞队列,其中元素只能在其延迟过期时使用

按照您希望的延迟将动物的每次移动发布到队列中。使用一个单独的线程
从队列中获取每个事件并执行它。队列将为您执行阻塞和调度-根本不需要
睡眠


每当您处理队列中的一个动物移动时,请按照所需的延迟将其重新发布到队列中。

我不完全清楚您的需要,但您可以只使用几个线程,甚至只需要一个额外的线程

我将把处理要求(所有动物都必须移动)设置到一个线程中,并在一个单独的线程中处理队列

DelayQueue-延迟元素的无界阻塞队列,其中元素只能在其延迟过期时使用

按照您希望的延迟将动物的每次移动发布到队列中。使用一个单独的线程
从队列中获取每个事件并执行它。队列将为您执行阻塞和调度-根本不需要
睡眠


每当你处理一只动物从队列中移出时,按你要求的延迟将其重新发布到队列中。

你要做的是从帧的角度考虑。每帧更新所有内容(例如1/60秒),然后一直睡到下一帧(动物更新后不必做任何事情,只要有机会)

假设一只兔子移动后需要休息2秒才能再次移动。每只兔子都有一个实例变量
restTime
,它在移动后将该变量设置为2秒。每帧它将减少该变量的帧时间(1/60秒)。当变量为零或更小时,它会再次移动。这意味着您可以在一个线程中完成所有操作,并且动物的移动不会相互依赖(当然,除非您希望它们移动)

如果你正在制作动画,最好测量实际的帧时间并使用它,而不是假设你实际得到的是你要求的1/60秒

下面是一个例子

public class Rabbit {
    private double timeBetweenMoves;
    private double sleepTime=0;
    private String name;

    public Rabbit(String name,double timeBetweenMoves) {
        this.name=name;
        this.timeBetweenMoves=timeBetweenMoves;
    }



    public void update(double timeSlice){
        sleepTime-=timeSlice;

        if (sleepTime<0){
            makeMove();
        }
    }

    private void makeMove(){
        sleepTime=timeBetweenMoves;

        //actually make the move

        System.out.println(name + " Moved");
    }


    public static void main(String[] args){

        double frameTime=1/60.0;

        List<Rabbit> rabbits=new ArrayList<>();

        rabbits.add(new Rabbit("Floppsy",2)); //moves every 2 seconds
        rabbits.add(new Rabbit("Hopper",5)); //moves every 5 seconds

        while(true){
            for(Rabbit rabbit:rabbits){
                rabbit.update(frameTime); //assumes frametime is actually what you asked for, can cause graphics to look stuttery
            }
            try {
                long milllisecondsToSleep=(long)(frameTime*1000);
                Thread.sleep(milllisecondsToSleep);
            } catch (InterruptedException ex) {
                Logger.getLogger(Rabbit.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

}
公共类兔子{
私人双时差移动;
私人双睡眠时间=0;
私有字符串名称;
公共兔子(字符串名称,双时差移动){
this.name=name;
timeBetweenMoves=timeBetweenMoves;
}
公共无效更新(双时间片){
睡眠时间-=时间片;

如果(睡眠时间你想做的是从帧的角度思考。每帧更新所有内容(例如1/60秒),然后一直睡到下一帧(动物在更新时不必做任何事情,它只是有机会更新)

假设一只兔子移动后需要休息2秒才能再次移动。每只兔子都有一个实例变量
restTime
,它在移动后将该变量设置为2秒。每帧它将减少该变量的帧时间(1/60秒)。当变量为零或更小时,它会再次移动。这意味着您可以在一个线程中完成所有操作,并且动物的移动不会相互依赖(当然,除非您希望它们移动)

如果你正在制作动画,最好测量实际的帧时间并使用它,而不是假设你实际得到的是你要求的1/60秒

下面是一个例子

public class Rabbit {
    private double timeBetweenMoves;
    private double sleepTime=0;
    private String name;

    public Rabbit(String name,double timeBetweenMoves) {
        this.name=name;
        this.timeBetweenMoves=timeBetweenMoves;
    }



    public void update(double timeSlice){
        sleepTime-=timeSlice;

        if (sleepTime<0){
            makeMove();
        }
    }

    private void makeMove(){
        sleepTime=timeBetweenMoves;

        //actually make the move

        System.out.println(name + " Moved");
    }


    public static void main(String[] args){

        double frameTime=1/60.0;

        List<Rabbit> rabbits=new ArrayList<>();

        rabbits.add(new Rabbit("Floppsy",2)); //moves every 2 seconds
        rabbits.add(new Rabbit("Hopper",5)); //moves every 5 seconds

        while(true){
            for(Rabbit rabbit:rabbits){
                rabbit.update(frameTime); //assumes frametime is actually what you asked for, can cause graphics to look stuttery
            }
            try {
                long milllisecondsToSleep=(long)(frameTime*1000);
                Thread.sleep(milllisecondsToSleep);
            } catch (InterruptedException ex) {
                Logger.getLogger(Rabbit.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }

}
公共类兔子{
私人双时差移动;
私人双睡眠时间=0;
私有字符串名称;
公共兔子(字符串名称,双时差移动){
this.name=name;
timeBetweenMoves=timeBetweenMoves;
}
公共无效更新(双时间片){
睡眠时间-=时间片;

如果(睡眠时间如果这是一个游戏循环,那么朝这个方向走可能更有意义:

public void run() {

    while (rabbitsNumber > 0) {

        for (int i=0; i<rabbitsNumber; i++)
             if (shouldMoveRabbit(i)) doRabbitMove();

        for (int i=0; i<wolvesNumber; i++)
             if (shouldMoveWolf(i)) doWolfMove();

        renderScreen();    
    }
}
public void run(){
而(兔子数>0){

对于(int i=0;i如果这是一个游戏循环,那么朝这个方向走可能更有意义:

public void run() {

    while (rabbitsNumber > 0) {

        for (int i=0; i<rabbitsNumber; i++)
             if (shouldMoveRabbit(i)) doRabbitMove();

        for (int i=0; i<wolvesNumber; i++)
             if (shouldMoveWolf(i)) doWolfMove();

        renderScreen();    
    }
}
public void run(){
而(兔子数>0){

对于(int i=0;i我同意@Groo。实现
shouldMoveXXX
比不必要地干扰并发性要好得多。您仍然可以这样基于时间(您的评论让您看起来像您想要的那样):

// time between each move
final int SLEEP_TIME = 1000;

//each animal has this variable, it is the last time they moved
long lastMoveTime;

public boolean shouldMoveRabbit(){
    if(System.currentTimeMillis() >= lastMoveTime + SLEEP_TIME)
         return true;
    return false;
}
public void doMoveRabbit(){
    lastMoveTime = System.currentTimeMillis();
    // move stuff
}

我同意@Groo。实现
shouldMoveXXX
比不必要地干扰并发性要好得多。您仍然可以将此时间设置为(您的评论让您看起来像您想要的那样):

// time between each move
final int SLEEP_TIME = 1000;

//each animal has this variable, it is the last time they moved
long lastMoveTime;

public boolean shouldMoveRabbit(){
    if(System.currentTimeMillis() >= lastMoveTime + SLEEP_TIME)
         return true;
    return false;
}
public void doMoveRabbit(){
    lastMoveTime = System.currentTimeMillis();
    // move stuff
}

这是一个不需要使用Sleep()或线程的解决方案,基本上我们将进行模拟,在视频游戏开发中使用相同的逻辑

public class Simulation 
{
    int clock;

    public static void simulate (Location r, Location w, int end_time)
    {
        clock = 0;

        Rabbit rabbit = new Rabbit (r);
        Wolf wolf = new Wolf (w);

        while (clock < end_time)
        {
            rabbit.update(clock, wolf.getLocation());
            wolf.update(clock, rabbit.getLocation());

            if(interlace(rabbit.getLocation(), wolf.getLocation()))
            {
                System.out.println("Wolf caught the rabbit at Time="+clock);
                break;
            }

            clock++;
        }
    }

    public static interlace (Location a, Location b)
    {
        // return TRUE if two locations interlace
    }
}
公共类模拟
{
国际时钟;
公共静态空隙模拟(位置r、位置w、int end_时间)
{
时钟=0;
兔子=新兔子(r);
狼=新狼(w);
while(时钟<结束时间)
{
update(clock,wolf.getLocation());
update(clock,rabbit.getLocation());
if(交错(rabbit.getLocation(),wolf.getLocation())
{
System.out.println(“狼在Time=“+时钟”时抓到了兔子);
打破
}
时钟++;