1 回答
TA贡献2012条经验 获得超12个赞
package com.wormwood.thread;
import java.util.LinkedList;
public class BufferLock //加互斥?的???
{
private LinkedList<Integer> stack = new LinkedList<Integer>();
public synchronized void put(int i) //同步方法
{
stack.push(new Integer(i)); //?value空?,value?得值
}
public synchronized int get() //同步方法
{
int value = 0;
if(!stack.isEmpty())
{
value = stack.removeFirst().intValue();
}
return value;
}
public static void main (String args[])
{
BufferLock buffer = new BufferLock();
(new Pproduced(buffer)).start();
(new Aprocessed(buffer)).start();
}
}
class Pproduced extends Thread //?送?程?
{
private BufferLock buffer;
public Pproduced(BufferLock buffer)
{
this.buffer = buffer;
}
public void run( )
{
for (int i=1;i<20;i++)
{
buffer.put( i );
System.out.println("P produced : " + i );
}
}
}
class Aprocessed extends Thread //接收?程?
{
private BufferLock buffer;
public Aprocessed(BufferLock buffer)
{
this.buffer = buffer ;
}
public void run()
{
for (int i=1; i<20;i++)
System.out.println("\t\t\t A processed : " + buffer.get()) ;
}
}
运行情况:
P produced : 1
P produced : 2
P produced : 3
P produced : 4
P produced : 5
P produced : 6
A processed : 1
A processed : 7
A processed : 6
P produced : 7
A processed : 5
P produced : 8
A processed : 8
P produced : 9
A processed : 9
P produced : 10
P produced : 11
P produced : 12
A processed : 10
P produced : 13
A processed : 13
P produced : 14
A processed : 14
P produced : 15
A processed : 15
P produced : 16
A processed : 16
P produced : 17
A processed : 17
P produced : 18
A processed : 18
P produced : 19
A processed : 19
A processed : 12
A processed : 11
A processed : 4
A processed : 3
A processed : 2
分析:这锁好像没什么用[ A processed : 7]还没有生产出来就消费了,
也试过:List list = Collections.synchronizedList(new LinkedList(...));
也有出现还没有生产出来就消费了....
楼主的程序哪个
private int value; //共享?量
private boolean isEmpty = true; //value是否?空的信?量
看意思是哪样,一般不会这样用的......
道理很简单:生产出来个的商品不可能只放在一个变量里,应该是集合
添加回答
举报