gpt4 book ai didi

java - 使用线程同时访问Java同步块(synchronized block)?

转载 作者:行者123 更新时间:2023-12-02 10:50:29 36 4
gpt4 key购买 nike

两个线程如何同时访问同步块(synchronized block)?也就是说,如何让一个线程有机会让另一个线程执行同步块(synchronized block),甚至在该线程完成同一同步块(synchronized block)的执行之前?

最佳答案

参见wait() , notify() ,和notifyAll() .

编辑:对您问题的编辑不正确。 sleep() method 释放监视器。

例如:

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();
}
}
}

关于java - 使用线程同时访问Java同步块(synchronized block)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782850/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com