java - 带有 RequestQue 的 while 循环中的 Thread.sleep ()

标签 java multithreading thread-sleep request-queueing

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

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

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

希望这有帮助:)

关于java - 带有 RequestQue 的 while 循环中的 Thread.sleep (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410138/

相关文章:

c++ - 只读操作的 std::map 线程安全

java - 如何在不同的线程上运行程序的某些部分并将变量引用到线程?

java - 当线程执行时,CPU 内部到底发生了什么?

java - Hashmap方法求和

java - 奇怪的 java.lang.IllegalArgumentException 异常

Python threading.local() 对我不起作用

Android Sleep/Wait/Delay 函数

java - 如何在 Android 上为 ActionBar 中的向上按钮添加监听器?

java - 没有操作栏的搜索 View

c - 在另一个线程中写入文件是否安全?