生产者、消费者多线程《小鸟请教》
public class ProducerCustomer
{
public static void main(String[] args)
{
SycStack st = new SycStack("馒头框");
//st.push(new ManTo(100));
Producer producer = new Producer(st);
Customer customer = new Customer(st);
Thread thread1 = new Thread(producer);
Thread thread2 = new Thread(customer);
thread1.start();
thread2.start();
}
}
class ManTo
{
public int id;
public ManTo(int id)
{
this.id = id;
}
public String toString()
{
return "===馒头->" + id;
}
}
class SycStack
{
public String name;
int index = 0;
ManTo[] blacket = new ManTo[6];
public SycStack(String str)
{
name = str;
}
public synchronized void push(ManTo mantou)
{
while(index == blacket.length)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
this.notify();
blacket[index] = mantou;
index++;
}
public synchronized ManTo pop()
{
while(index == 0)
{
try
{
this.wait();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
this.notify();
index--;
return blacket[index];
}
}
class Producer implements Runnable
{
SycStack st = null;
Producer(SycStack st)
{
this.st = st;
}
public void run()
{
for(int i=0; i<20; i++)
{
ManTo manTo = new ManTo(i);
st.push(manTo);
System.out.println("我生产了" + manTo);
}
}
}
class Customer implements Runnable
{
SycStack st = null;
Customer(SycStack st)
{
this.st = st;
}
public void run()
{
for(int i=0; i<20; i++)
{
ManTo manTo = st.pop();
System.out.println("我消费了" + manTo);
}
}
}
运行结果如下:
--------------------编程问答--------------------
this.notify();
blacket[index] = mantou;
index++;
需要调整个顺序,修改为:
blacket[index] = mantou;
index++;
this.notify();
对于pop操作同理也要这样做,只有等栈的操作结束了才能唤醒其他线程
--------------------编程问答-------------------- 你这么说貌似有道理,可是,还是存在先消费,后生产的问题,另外,pop里面,用的是return语句,如果this.notify()放在return后面不会得到执行啊! --------------------编程问答-------------------- 我理解错了,不是那段代码的问题,而是你System.out.println();打印语句的问题,两个打印语句也应该放在同步方法push和pop中,否则有可能后边的打印语句先执行,得到错误的打印结果。
得出结论:测试线程手段也要保证没有问题才行 --------------------编程问答-------------------- 多谢,您说的是对的,可是为什么呢?逻辑上都是一样的啊! --------------------编程问答-------------------- 不一样的,println语句如果没有同步是不会按预期效果顺序打印的
补充:Java , Java SE