结果不对亚?一个简单短小的例子——采用信号量和同步方法使发送线程与接收线程同步运行
一个缓冲区类BufferLock采用synchronized同步方法,一个发送线程Sender,一个接收线程Receiver,运行结果都不一致,偶尔才对,问题出在哪里呢?运行结果有时是:
Sender put: 1
Receiver get: 1
Receiver get: 2
Sender put: 2
Sender put: 3
Receiver get: 3
Sender put: 4
Receiver get: 4
Sender put: 5
Receiver get: 5
public class BufferLock
{
private int value;
private boolean isEmpty=true;
public synchronized void put(int i)
{
while(!isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
value=i;
isEmpty=false;
notify();
}
public synchronized int get()
{
while(isEmpty)
try
{
this.wait();
}
catch(InterruptedException e){}
isEmpty=true;
notify();
return value;
}
}
class Sender extends Thread
{
private BufferLock buffer;
public Sender(BufferLock buffer)
{
this.buffer=buffer;
}
public void run()
{
for(int i=1;i<6;i++)
{
buffer.put(i);
System.out.println("Sender put: "+i);
}
}
}
class Receiver extends Thread
{
private BufferLock buffer;
public Receiver(BufferLock buffer)
{
this.buffer=buffer;
}
public void run()
{
for(int i=1;i<6;i++)
System.out.println("\t\t Receiver get: "+buffer.get());
}
public static void main(String args[])
{
BufferLock buffer=new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
}
public class BufferLock {无论哪个线程锁了buffer,另外一个线程就只能wait了,直到noticy。也就不会出现多次receive或者多次sender的现象了。
public static void main(String args[]) {
BufferLock buffer = new BufferLock();
(new Sender(buffer)).start();
(new Receiver(buffer)).start();
}
private int value;
private boolean isEmpty = true;
public void put(int i) {
while (!isEmpty)
try {
this.wait();
} catch (InterruptedException e) {
}
value = i;
isEmpty = false;
notify();
}
public int get() {
while (isEmpty)
try {
this.wait();
} catch (InterruptedException e) {
}
isEmpty = true;
notify();
return value;
}
}
class Sender extends Thread {
private BufferLock buffer;
public Sender(BufferLock buffer) {
this.buffer = buffer;
}
public void run() {
synchronized (buffer) {
for (int i = 1; i < 6; i++) {
buffer.put(i);
System.out.println("Sender put: " + i);
}
}
}
}
class Receiver extends Thread {
private BufferLock buffer;
public Receiver(BufferLock buffer) {
this.buffer = buffer;
}
public void run() {
synchronized (buffer) {
for (int i = 1; i < 6; i++)
System.out.println("\t\t Receiver get: " + buffer.get());
}
}
}