【发布时间】:2014-04-23 21:12:24
【问题描述】:
现在我研究信号量。我搜索了有关此主题的以下链接:
此链接的作者撰写了有关使用信号量进行信号传输的文章。为了展示它是如何工作的,他编写了自定义信号量。
自定义信号量代码:
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException{
while(!this.signal) wait();
this.signal = false;
}
}
关于如何在他编写的代码中使用它:
public class SendingThread {
Semaphore semaphore = null;
public SendingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run(){
while(true){
//do something, then signal
this.semaphore.take();
}
}
}
public class RecevingThread {
Semaphore semaphore = null;
public ReceivingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run(){
while(true){
this.semaphore.release();
//receive signal, then do something...
}
}
}
主要:
Semaphore semaphore = new Semaphore();
SendingThread sender = new SendingThread(semaphore);
ReceivingThread receiver = new ReceivingThread(semaphore);
receiver.start();
sender.start();
据我了解,执行顺序应遵循
send - receive
send - receive
send - receive
...
我尝试使用此蓝图编写自己的代码
public class SendReceiveWithCustomSemaphore {
public static void main(String[] args) {
MySemaphore mySemaphore = new MySemaphore();
new Send(mySemaphore).start();
new Receive(mySemaphore).start();
}
}
class MySemaphore {
boolean flag = false;
public synchronized void take() throws InterruptedException {
flag = true;
notify();
}
public synchronized void release() throws InterruptedException {
while (!flag) {
wait();
}
flag = false;
}
}
class Send extends Thread {
MySemaphore mySemaphore;
public Send(MySemaphore semaphore) {
this.mySemaphore = semaphore;
}
@Override
public void run() {
int i = 0;
while (i++ < 10) {
System.out.println("send");
try {
mySemaphore.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Receive extends Thread {
MySemaphore mySemaphore;
public Receive(MySemaphore semaphore) {
this.mySemaphore = semaphore;
}
@Override
public void run() {
while (true) {
try {
mySemaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("receive");
}
}
}
输出:
send
send
send
send
send
send
send
send
send
send
receive
因此,这不是我预期的行为。
是我写错了代码还是没看懂概念?
作者想说什么?
【问题讨论】:
-
@rpg711 ideone.com/d76Elw
-
System.out 对于知道线程执行的顺序是不可靠的。 stackoverflow.com/a/18831093/1168342
-
在 Receive 中的
while循环之前尝试Thread.sleep(1000);。
标签: java multithreading concurrency synchronization semaphore