Thread.sleep () 在 while 循环中与 RequestQue

Thread.sleep () in while loop with RequestQue

我想做的是延迟 15 秒的 while 循环,在循环内我想执行 volley 请求..循环工作但没有延迟

这是我的代码:(client2是凌空请求方法)

new Thread(new Runnable() {@Override
    public void run() {
        while (h < taxiidlist.size() && assined == false && requested == true) {
            handler2.post(new Runnable() {@Override
                public void run() {

                    client2(user.id, taxiidlist.get(h));

                    h++;
                }

            });
                try {
                    Thread.sleep(15000);
                } catch(InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }).start();

我不明白为什么代码不起作用。一个可能的问题可能是您忘记在传递内部 Runnable 实例的 handler.post() 中调用 run()

尝试使用此示例代码(循环只执行一次),看看您是否能发现您的问题。

private static List<String> taxiidlist = new ArrayList<>();
static int h = 0;

public static void main(String[] args) {

    int id = 0;
    boolean assined = false;
    boolean requested = true;
    taxiidlist.add("One");

    new Thread(new Runnable() {
        @Override
        public void run() {
            while (h <= taxiidlist.size() && assined == false && requested == true) {
                post(new Runnable() {
                    @Override
                    public void run() {
                        client2(id, taxiidlist.get(h));
                        h++;

                        try {
                            Thread.sleep(1500);
                            System.out.println("slept!");
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });

                break;
            }
        }
    }).start();

}

static void post(Runnable runnable) {
    System.out.println("post!");
    runnable.run();

}

static void client2(int id, String s) {
    System.out.println("client2!");
}

希望这对您有所帮助:)