gpt4 book ai didi

java - 如何让特定线程成为下一个进入同步块(synchronized block)的线程?

转载 作者:搜寻专家 更新时间:2023-10-30 21:07:50 24 4
gpt4 key购买 nike

我在面试中被问到这个问题。

There are four threads t1,t2,t3 and t4. t1 is executing a synchronized block and the other threads are waiting for t1 to complete. What operation would you do, so that t3 executes after t1.

我回答说 join 方法应该可以解决问题,但看起来这不是正确的答案。他给出的原因是,join 方法和 setPriority 方法不适用于等待状态的线程。

我们能做到吗?如果是,如何?

最佳答案

您可以使用锁和条件。将相同的条件传递给 t1 和 t3:

class Junk {

private static class SequencedRunnable implements Runnable {
private final String name;
private final Lock sync;
private final Condition toWaitFor;
private final Condition toSignalOn;

public SequencedRunnable(String name, Lock sync, Condition toWaitFor, Condition toSignalOn) {
this.toWaitFor = toWaitFor;
this.toSignalOn = toSignalOn;
this.name = name;
this.sync = sync;
}

public void run() {
sync.lock();
try {
if (toWaitFor != null)
try {
System.out.println(name +": waiting for event");
toWaitFor.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ": doing useful stuff...");
if (toSignalOn != null)
toSignalOn.signalAll();
} finally {
sync.unlock();
}
}
}

public static void main(String[] args) {
Lock l = new ReentrantLock();
Condition start = l.newCondition();
Condition t3AfterT1 = l.newCondition();
Condition allOthers = l.newCondition();
Thread t1 = new Thread(new SequencedRunnable("t1", l, start, t3AfterT1));
Thread t2 = new Thread(new SequencedRunnable("t2", l, allOthers, allOthers));
Thread t3 = new Thread(new SequencedRunnable("t3", l, t3AfterT1, allOthers));
Thread t4 = new Thread(new SequencedRunnable("t4", l, allOthers, allOthers));

t1.start();
t2.start();
t3.start();
t4.start();

l.lock();
try {
start.signalAll();
} finally {
l.unlock();
}
}
}

关于java - 如何让特定线程成为下一个进入同步块(synchronized block)的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6574218/

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