Thread.sleep () in while loop with RequestQue

1.2k views Asked by At

what i'm trying to do is while loop with delay of 15 seconds and inside the loop i want to execute volley request .. the loop is working but with no delay

this is my code : (client2 is the volley request method )

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();
1

There are 1 answers

2
Prathap On BEST ANSWER

I don't see why the code isn't working. One possible issue might be that you have forgotten to invoke run() within the handler.post() where your inner Runnable instance is being passed.

Try with this sample code (loop executed just once) and see if you can spot the issue in yours.

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

Hope this helps :)