使用线程同时访问Java同步块?

Hea*_*Boy 2 java multithreading block simultaneous execution

两个线程如何同时访问同步块?也就是说,即使在此线程完成相同同步块的执行之前,如何让一个线程为其他线程提供执行同步块的机会?

Rya*_*art 6

请参阅wait(),notify()notifyAll().

编辑:您的问题的编辑不正确.在sleep()方法不能释放监视器.

例如:

private static final Object lock = new Object();

public static void main(String[] args) {
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    executorService.execute(new One());
    executorService.execute(new Two());
}

static class One implements Runnable {
    @Override
    public void run() {
        synchronized (lock) {
            System.out.println("(One) I own the lock");
            System.out.println("(One) Giving up the lock and waiting");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                System.err.println("(One) I shouldn't have been interrupted");
            }
            System.out.println("(One) I have the lock back now");
        }
    }
}

static class Two implements Runnable {
    @Override
    public void run() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            System.err.println("(Two) I shouldn't have been interrupted");
        }
        synchronized (lock) {
            System.out.println("(Two) Now I own the lock (Two)");
            System.out.println("(Two) Giving up the lock using notify()");
            lock.notify();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)