xin
xin

Reputation: 309

How to suppress main thread until a TimerTask thread which is invoked by main thread is finished?

In my main thread I send some data to server via HttpURLConnection, then I start a timer to execute a TimerTask periodically to check the response of server. When I get the expected string I call timer.cancel(). After this, main thread resume from where the timer is started.

I imagine following simplified code with the same mechanism just for this post:

public class Test {
    public static void main(String[] args) throws InterruptedException {  
        System.out.println("start");
        Timer timer = new Timer();
        TmTask timerTask = new TmTask(timer);       
        Thread thread = new Thread(timerTask,"thread_1");
        thread.start();
        thread.join();      
        System.out.println("end");
    }  
}

class TmTask extends TimerTask{
    Timer t;

    public TmTask(Timer t){
        this.t = t;
    }

    @Override
    public void run() {
        t.schedule(new A(t), 100, 1000);

    }   
}
class A extends TimerTask{
    private Timer t;
    private int i = 0;
    public A(Timer t) {
        this.t = t;
    }
    @Override
    public void run() {
        System.out.println("abc" );
        i++;
        if (i == 3) t.cancel();
    }   
}

My expection is :

start
abc
abc
abc
end

But I get:

start
end
abc
abc
abc

Finally I realized that in my code there are 3 threads created but I expected 2 (main thread, and Timer thread), and the join() method works on the thread named thread_1 instead of the timer thread. But I have no idea how to improve it.

Can anyone help me? Thanks in advance.

Upvotes: 0

Views: 1439

Answers (1)

Veselin Davidov
Veselin Davidov

Reputation: 7071

The whole purpose of creating a new Thread is to start it separately from the main thread - to get parallel execution. You got 3 threads because the timertask creates its own thread. If you want your current (main) thread to stop and wait for result then you can just do something like:

boolean result = false;
while( ! result ) {
 result=checkForResult();
 Thread.sleep(1000);
}

This will pause the current thread and cause it to block. Usually for such external tasks and async calls you DO NOT want the main thread to stop execution and wait because you don't know when will you get result and it might wait indefinitely. So probably your result is the desired one? :)

Upvotes: 1

Related Questions