/* @src http://eric-619.iteye.com/blog/693680
* java多线程:生产者消费者核心程序代码及wait()---notify()、notifyAll()方法应用测试
* 把消费者来回跑的次数多,更能体现出多线程的次序性(测试次序正确性的原则)
* notify()方法开启对方线程!!!,因为对方有wait()
*/
public class ProCon{
public static void main(String[] args){
SyncStack stack = new SyncStack();
Consumer p = new Consumer(stack);
Producer c = new Producer(stack);
You y = new You(stack);
new Thread(c).start();
new Thread(y).start();
new Thread(p).start();
}
}
class Producer implements Runnable{
private SyncStack stack;
public Producer(SyncStack stack){
this.stack = stack;
}
public void run(){
for (int i = 0; i < stack.pro().length; i++){
stack.push("产品"+i);
}
}
}
class You implements Runnable{
SyncStack s;
public You(SyncStack s){
this.s = s;
}
public void run(){
for(int i = 0; i < s.pro().length; i++){
new SyncStack().yp();
}
}
}
class Consumer implements Runnable{
private SyncStack stack;
public Consumer(SyncStack stack) {
this.stack = stack;
}
public void run(){
for(int i = 0; i < stack.pro().length; i++){
System.out.println(stack.pop());
}
}
}
class SyncStack{
private String[] str = new String[10];
private int index;
public synchronized String pop(){
if(index == 0){
try{
wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
//notify();
return "消费了-------------------"+str[--index];
}
public synchronized void push(String sst){
//notifyAll();
str[index] = sst;
index ++;
System.out.println("生产了:"+sst);
}
public synchronized void yp(){
// if(index == 0){
// try{
// wait();
// }catch (InterruptedException e){
// e.printStackTrace();
// }
// }
System.out.println("凑凑热闹的!!!!!!!!!!!"+"------"+index);
}
public String[] pro(){
return str;
}
}
java生产者消费者核心代码
最新推荐文章于 2024-09-13 23:03:04 发布