Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>How to get a Java Thread to notify itself?</p> </blockquote> <p>You can't get a Thread to notify itself since it is blocked in <code>wait()</code>. You <em>can</em> have another thread notify the thread by synchronizing on the same object that the thread is locking on and calling <code>notify()</code>. See the below code for a sample.</p> <p>That said, I'd recommend using a <code>BlockingQueue</code> to share data in this respect. It takes care of all of the locking and signaling. All the thread does is call <code>take()</code> and it will wait for the next operation to be added to the queue with a <code>put()</code>.</p> <p>Lastly, it's always recommended to implement <code>Runnable</code> instead of extending <code>Thread</code>. Once you turn your thread into a runnable you can use the <code>ExecutorService</code> classes as @Peter mentions in his answer. With an <code>ExecutorService</code> your code would look like:</p> <pre><code> public class OperationHandler implements Runnable { public void run() { // no looping or dequeuing needed // just execute the job } } // create a thread pool with a single thread worker ExecutorService threadPool = Executors.newSingleThreadExecutor(); // or create a thread pool with 10 workers // ExecutorService threadPool = Executors.newFixedThreadPool(10); // or you can create an open-ended thread pool // ExecutorService threadPool = Executors.newCachedThreadPool(); ... // do this once or many times threadPool.submit(new OperationHandler()); ... </code></pre> <p>But if you still want to tweak your code to get it to work:</p> <pre><code> private final Object lockObject = new Object(); public void run() { synchronized (lockObject) { ... lockObject.wait(); } } // called by another thread public void operationRequired() { synchronized (lockObject) { ... lockObject.notify(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload