Reputation: 980
I want to make a thread to pause in a GUI by pressing a button and the thread can be used or free until the same button is clicked is that possible in java. and any ideas how its done ? I am using Swing GUI
Upvotes: 0
Views: 169
Reputation: 49095
You probably do not want to do the accepted answer of Thread.sleep and should probably learn how the Swing Event Queue works.
You want to look at:
http://docs.oracle.com/javase/6/docs/api/javax/swing/SwingUtilities.html
Particularly:
Also see these stackoverflow posts:
Upvotes: 1
Reputation: 15673
Thread.sleep(4000);
http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
Or the newer
TimeUnit.SECONDS.sleep(4);
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Upvotes: 0
Reputation: 5296
In multithreading you can't really safely 'force' a thread to stop/pause without cooperation from the thread itself. (Java has ill-conceived methods to attempt this such Thread.suspend(). You can read about why they're deprecated.).
A common way pause a thread is to set a boolean flag and have that thread poll that state. That way it can safely pause or shutdown without causing deadlocks etc.
Also, as @Perry states a worker thread may go to sleep simply by having nothing to do. Ex. a thread to process enqueued requests. If the queue is empty then it just quietly waits for new requests.
Upvotes: 0
Reputation: 7242
There is no easy way to pause a Thread and have it immediately free for other tasks, and then be able to resume that same thread on demand.
You can pause the thread using Thread.sleep(), and then have other threads do work, but the paused thread will be blocked and unable to do additional work until it is unpaused or interrupted.
Since a thread has to keep track of its stack and all of the variables pursuant to its execution, it would be quite difficult to pause it in one flow of execution and have it do other work before unpausing. Notably, there is no reason to even attempt to do this, since your attempt would simply be duplicating what thread already does (tracking the stack etc). So what you need to do is make another thread to do what you want when you pause the first thread.
Long story short, pause with Thread.sleep() and create additional threads to do your other work (you cannot use the paused thread for other work while it is paused).
Upvotes: 1
Reputation: 901
You can simulate a pause by not doing anything in it.
To simulate, all you need is a boolean that is toggled by the button that the thread has reference to. If it's true, then carry out what you would normally, otherwise just sleep for a bit.
That's the only way I know how.
Upvotes: 0