了解Java Wait和Notify方法

Mad*_*ddy 7 java multithreading wait

我有以下计划:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SimpleWaitNotify implements Runnable {

final static Object obj = new Object();
static boolean value = true;

public synchronized void flag()  {
    System.out.println("Before Wait");
    try {
        obj.wait();
    } catch (InterruptedException e) {
        System.out.println("Thread interrupted");
    }
    System.out.println("After Being Notified");
}

public synchronized void unflag() {
    System.out.println("Before Notify All");
    obj.notifyAll();
    System.out.println("After Notify All Method Call");
}

public void run() {
    if (value) {
        flag();
    } else {
        unflag();
    }
}

public static void main(String[] args) throws InterruptedException {
    ExecutorService pool = Executors.newFixedThreadPool(4);
    SimpleWaitNotify sWait = new SimpleWaitNotify();
    pool.execute(sWait);
    SimpleWaitNotify.value = false;
    SimpleWaitNotify sNotify = new SimpleWaitNotify();
    pool.execute(sNotify);
    pool.shutdown();

}
Run Code Online (Sandbox Code Playgroud)

}

当我等待obj时,我会Exception in thread "pool-1-thread-1" java.lang.IllegalMonitorStateException: current thread not owner为两个线程中的每一个获得以下异常.

但是如果我使用SimpleWaitNotify的监视器,则程序执行被暂停.换句话说,我认为它暂停当前的执行线程,反过来执行器.任何有助于理解正在发生的事情的帮助都将得到适当的赞赏.

这是一个理论和javadoc看起来很简单的领域,并且由于没有太多的例子,概念上在我身上留下了很大的差距.

Jon*_*eet 12

你打电话waitnotifyAllobj,但你在同步this(因为你已经得到了同步方法).

为了等待或通知,您需要首先"拥有"监视器.取消同步方法,并在obj上同步:

public void flag()  {
    System.out.println("Before Wait");
    synchronized (obj) {
        try {
            obj.wait();
        } catch (InterruptedException e) {
            System.out.println("Thread interrupted");
        }
    }
    System.out.println("After Being Notified");
}

public void unflag() {
    System.out.println("Before Notify All");
    synchronized (obj) {
        obj.notifyAll();
    }
    System.out.println("After Notify All Method Call");
}
Run Code Online (Sandbox Code Playgroud)

  • @Maddy:您应该能够等待并通知"this" - 但这通常是一个坏主意,因为"this"通常是其他代码可以有效访问的引用.保持对只有您的代码知道的对象的私有引用才是好习惯. (4认同)