伍柒貳
伍柒貳

Reputation: 49

Is Thread.sleep(n) blocking other things from going? Something better to replace it?

I have a little application counting time by pressing a button,
I just use thread.sleep() to count.

When the button is pressed, it triggers the ActionListener which is a class that perform a thread.run(). The thread.sleep() is then started from inside the run() function.

//The Thread
class twentyMins implements Runnable
    @Override
    public void run() {
        try {
            Thread.sleep(1000*60*20);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }
}

//The ActionListener
class Reset implements ActionListener {

    public static twentyMins count = new twentyMins();

    @Override
    public void actionPerformed(ActionEvent event) {
        count.run();
    }

}

The issue is, the button will not bounce up and be able to be pressed again.
And the application can't even be stopped by pressing the EXIT button on the JFrame.

Straightforwardly, I think my application is frozen while the thread.sleep() is running.

Is there something better then Thread.sleep()?

Upvotes: 1

Views: 62

Answers (3)

Vkki
Vkki

Reputation: 1

To perform sleep() on main thread will block the UI. You could create another thread or just use java.util.Timer class to finish this task.

Upvotes: 0

Daniel Earwicker
Daniel Earwicker

Reputation: 116714

You didn't actually start a background thread here. Any object can implement Runnable (and the run method) but that doesn't make it a thread. Hence when your Reset button is clicked, it locks up the single thread responsible for the UI.

You need to pass your Runnable object to the constructor of the Thread class (java.lang.Thread), as described in the official docs.

Upvotes: 6

Aniket Thakur
Aniket Thakur

Reputation: 68975

What did you expect? You are calling

count.run();

Which will run in same main thread thereby blocking it for 20 mins. Consider creating a thread and calling start() on it.

Upvotes: 1

Related Questions