java 迭代前循环延迟不起作用

dldeef67  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(136)

我想要的只是在下一次迭代之前等待一段时间而不阻塞线程,因为其他进程必须继续。
已尝试使用Timer,但在for循环中没有任何效果。
我卡住了。
有一个必须执行的方法,执行时间大约为20秒。
我的for循环如下

int[] ids ={1,2,3,4,5,6,87,234,6,346,3,4634,12};

        for (int i= 0, len = ids.length; i<len;i++) {
            Log.e(" Need to wait: ", " for every widget to update~");
            final int[] timesRun = {0};
            Timer timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    timesRun[0] = timesRun[0] + 1;
                    Log.e("timesRun", String.valueOf(timesRun[0]));

                    Log.i("tag", "runs every 5 seconds");
                    if (timesRun[0] == 10) {
                        myProcessfor20Seconds();
                        timer.cancel();

                    }
                }
            }, 0, 5000);

            Log.i("tag", "Exiting the Timer");

        }

这也

int[] ids ={1,2,3,4,5,6,87,234,6,346,3,4634,12};

    for (int i= 0, len = ids.length; i<len;i++) {
        Log.e(" Need to wait: ", " for every widget to update~");
       final AtomicInteger timesRun = new AtomicInteger(0);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                timesRun.addAndGet(1);

                Log.e("timesRun", String.valueOf(timesRun.get()));

                Log.i("tag", "runs every 5 seconds");
                if (timesRun.intValue() ==  10) {
                    timer.cancel();

                }
            }
        }, 0, 5000);

        Log.i("tag", "Exiting the Timer");

    }

但是logcat是这样的
一个二个一个一个
在完成所有迭代之后执行。
看起来我需要一些同步的东西,但我卡住了,我还在学习。请帮助。

bq3bfh9z

bq3bfh9z1#

我会保持简单:启动一个线程以在执行之间留有间隙的情况下运行您的方法,并在主线程中等待它完成。

Thread t = new Thread(() -> {
    for (int i = 0, len = ids.length; i < len; i++) {
        myProcessfor20Seconds();
        try {
            if (i < len - 1) // don't sleep after the last execution
                Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}); // create the Thread with your background code as a Runnable

t.start(); // start the background thread

// Do other stuff while the Thread is running

try {
    t.join(); // wait for thread to finish
} catch (InterruptedException e) {
    throw new RuntimeException(e);
}

还有更优雅的方法来处理异常,但这是最基本的。

相关问题