信号量是一个操作系统术语,即在多线程环境下,通过某种设施,来保证多个线程不会并发执行 在Java中,信号量机制可以通过同步锁对象来实现: 一个线程可以通过调用lock.wait让其它线程先执行,其它线程执行完,可以再调用lock.notify让之前的线程继续执行
以下代码模拟了一个简单的信号量应用场景
public class Z {
private static final Device device = new Device();
private static final Object packetReceivedSemaphore = new Object();
private static boolean received;
//Thread-A向设备写入数据,Thread-B读取设备反馈,100毫秒内Thread-B读取到设备反馈,则视为数据写入成功
public static void main(String[] args) {
Threads.post(() -> {
while (true) {
try {
synchronized (packetReceivedSemaphore) {
received = false;
device.write();
packetReceivedSemaphore.wait(100);
if (received)
System.out.println("Packet Received");
else
System.out.println("Packet Lost");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
Threads.post(() -> {
while (true) {
try {
synchronized (packetReceivedSemaphore) {
received = device.read() != null;
packetReceivedSemaphore.notify();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//模拟读写,实际应用情景可能是一个线程写入设备,一个线程读取设备反馈,这里用一个类来简单模拟设备
public static class Device {
public void write() {
}
public String read() {
int ran = MathUtil.randomInt(0, 1);
if (ran == 0)
return "ok";
return null;
}
}
}
运行结果