How to notify a specific thread in Java

后端 未结 4 829
闹比i
闹比i 2020-12-21 04:07

How I can call a particular thread in inter-thread communication?

In the program below I have two threads t1 and t2.

When I call

4条回答
  •  没有蜡笔的小新
    2020-12-21 05:06

    You don't / can't notify a specific thread. You call notify() on a lock object. This wakes up one of the threads1 that is waiting on the lock. In your case, the lock object is a Thread ... which rather confuses the picture. However, see below.

    But your problem (the IllegalMonitorStateException) happens because the thread doing the notifying (i.e. the current thread) does not hold the lock. It is a (hard) requirement that the current thread must hold the lock when it notifies a lock.

    For more details, read the javadocs for Object.wait(timeout) or (for example) this: http://howtodoinjava.com/core-java/multi-threading/how-to-work-with-wait-notify-and-notifyall-in-java/

    1 - If multiple threads are waiting on your lock, one thread is chosen "randomly" by the scheduler. Alternatively notifyAll will wake up all of the waiting threads.


    I would NOT use a Thread object as a lock object. It will possibly work, but there is also a chance that something else (maybe something in the runtime system) is also locking / waiting / notifying the Thread objects. Then things would get very confusing.

    (Indeed, read the javadoc for Thread.join(long) !)

    It is BETTER to create lock objects specifically for this purpose; e.g.

    private final Object lock = new Object();
    

    Also, writing classes that extend Thread is usually a bad idea. It is usually better to implement the Runnable interface, instantiate it, and pass the instance as a parameter to the Thread constructor; e.g.

    Thread t = new Thread(new Runnable() {
        public void run() {
            System.out.println("Hello world");
        }});
    t.start();
    

    One advantage of implementing Runnable rather than extending Thread is that you can use your code more easily with something that manages the thread life cycles for you; e.g. an ExecutorService, a fork-join thread pool or a classic thread pool.

    A second one is that light-weight thread logic can be implemented concisely as an anonymous class ... as in my example.

提交回复
热议问题