gpt4 book ai didi

java - 当线程更改状态时,有什么方法可以在进程中获取通知吗?

转载 作者:行者123 更新时间:2023-11-30 05:56:05 27 4
gpt4 key购买 nike

当线程改变状态时,有什么方法可以在进程中获取通知吗?我正在编写一个监视线程状态变化的程序。我可以经常轮询每个线程,但我更喜欢更具 react 性的东西。

最佳答案

是的,使用条件变量,这是一个示例:

import java.util.concurrent.locks.*;
public class CubbyHole2 {
private int contents;
private boolean available = false; // this is your state
private Lock aLock = new ReentrantLock(); // state must be protected by lock
private Condition condVar = aLock.newCondition(); // instead of polling, block on a condition

public int get(int who) {
aLock.lock();
try {
// first check state
while (available == false) {
try {
// if state not match, go to sleep
condVar.await();
} catch (InterruptedException e) { }
}
// when status match, do someting

// change status
available = false;
System.out.println("Consumer " + who + " got: " +
contents);
// wake up all sleeper than wait on this condition
condVar.signalAll();
} finally {
aLock.unlock();
return contents;
}
}

public void put(int who, int value) {
aLock.lock();
try {
while (available == true) {
try {
condVar.await();
} catch (InterruptedException e) { }
}
contents = value;
available = true;
System.out.println("Producer " + who + " put: " +
contents);
condVar.signalAll();
} finally {
aLock.unlock();
}
}
}

关于java - 当线程更改状态时,有什么方法可以在进程中获取通知吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150276/

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