我使用wait
和notify
方法进行研究以进行同步。
我写了一些小例子并且不明白为什么我看到这个输出:
take 1
release 1
release 2
我的代码:
主:
public class CustomSemaphoreTest {
public static void main(String[] args) throws InterruptedException {
Semaphore semaphore = new Semaphore();
SendingThread sender = new SendingThread(semaphore);
RecevingThread receiver = new RecevingThread(semaphore);
sender.start();
Thread.sleep(300);
receiver.start();
}
}
发件人:
class SendingThread extends Thread {
volatile Semaphore semaphore = null;
int count = 1;
public SendingThread(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
this.semaphore.take();
}
}
接收器:
class RecevingThread extends Thread {
volatile Semaphore semaphore = null;
int count = 1;
public RecevingThread(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
while (true) {
try {
this.semaphore.release();
Thread.sleep(20);
} catch (InterruptedException e) {
}
// System.out.println("get signal " + count++);
}
}
}
旗语:
class Semaphore {
private boolean signal = false;
int rCount = 1;
int sCount = 1;
public synchronized void take() {
System.out.println("take " + sCount++);
this.signal = true;
this.notify();
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void release() throws InterruptedException {
System.out.println("release " + rCount++);
notify();
while (!this.signal) {
wait();
}
this.signal = false;
}
}
我是如何想象执行这个程序的?:
时间0:thread1:sender.start()
- > ...->
public synchronized void take() {
System.out.println("take " + sCount++);
this.signal = true;
this.notify(); //try wake up waiting threads but noone sleep thus have not affect
try {
wait(); // release monitor and await notify
} catch (InterruptedException e) {
e.printStackTrace();
}
}
因此,我在屏幕take 1
时间300:主题2 receiver.start();
- >
public synchronized void release() throws InterruptedException {
System.out.println("release " + rCount++); //section is rid thus this lines outputes
notify(); // notify thread1
while (!this.signal) {
wait(); // pass the control to thread1 and await notification .....
}
this.signal = false;
}
因此我没有期望看到release 2
请澄清我的误解。
答案 0 :(得分:3)
在 signal = false
之后设置wait()
。
事件顺序。
sender
来电take()
sender
打印signal
设置为true
receiver
已收到通知sender
来电wait()
receiver
醒来receiver
打印sender
已收到通知signal
是true
所以没有wait()
signal
设置为false
release()
方法结束receiver
循环receiver
打印signal
false
wait()
sender
立即醒来并立即退出所以你有几个问题
sender
无法循环signal