Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #32938
| From | Eric Sosman <esosman@comcast-dot-net.invalid> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Re: thread sleeping until event |
| Date | 2015-10-27 08:36 -0400 |
| Organization | A noiseless patient Spider |
| Message-ID | <n0nr0r$a23$1@dont-email.me> (permalink) |
| References | <65ba7e2b-caee-4656-b740-b34110b2982c@googlegroups.com> |
On 10/27/2015 5:41 AM, Philipp Kraus wrote:
> Hello,
>
> I have got a main thread running which can be stay in a pause definition. At the moment the main structure is:
>
> volatile boolean mypause = true;
>
> public voud run()
> {
> while (true)
> {
> if (mypause)
> Thread.sleep(1000);
>
> // thread is working
>
> }
> }
>
> public void pause()
> {
> mypause = !mypause;
> }
>
>
>
>
> If mypause is switch to false the thread should running. So my question is, how can I do a good pause state, so the thread create minimal system load.
There are several ways. The "traditional" approach is to use
wait() and notify() or notifyAll():
private boolean paused = true;
public void run() {
while (true) {
synchronized(this) {
while(paused) {
this.wait();
}
}
do_work();
}
}
public synchronized void pauseOrResume() {
paused = !paused;
this.notifyAll();
}
(I wrote the "this." pieces for clarity's sake; they could be omitted.)
A few remarks:
- Your pause() method, which I renamed to pauseOrResume() to better
indicate what it does, seems peculiar. An external agency might
know when it wants the thread to start working, but it won't know
when to tell the thread *not* to work: It doesn't know whether the
thread has or has not yet seen the "Go" sign.
- Along the same lines, I find it surprising that the worker thread
does not set `paused' to true after (or before) do_work(). As it
stands, the thread will just run and run and run until an external
caller flips the `paused' switch.
- The pause() method in your original code is *not* thread-safe. It
manipulates a `volatile' variable, yes, but it both reads *and*
writes the value. The read is thread-safe and so is the write,
but the two operations taken as a pair are not. That's why I used
`synchronized' to guard the variable.
--
esosman@comcast-dot-net.invalid
"Don't be afraid of work. Make work afraid of you." -- TLM
Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
thread sleeping until event Philipp Kraus <philipp.kraus.flashpixx@gmail.com> - 2015-10-27 02:41 -0700
Re: thread sleeping until event Eric Sosman <esosman@comcast-dot-net.invalid> - 2015-10-27 08:36 -0400
Re: thread sleeping until event Philipp Kraus <philipp.kraus.flashpixx@gmail.com> - 2015-10-27 14:22 -0700
csiph-web