1

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

这是我的代码:(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();
4

1 回答 1

1

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

试试这个示例代码(循环只执行一次),看看你是否能发现你的问题。

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!");
}

希望这可以帮助 :)

于 2016-12-31T18:17:14.230 回答