生产者 消费者模型

    技术2022-05-11  2

    package com.cric.testThread;

    public class SynTest {

     /**  * @param args  */ public static void main(String[] args) {  // TODO Auto-generated method stub  SyncTest stack=new SyncTest();  Runnable p=new Producer(stack);  Runnable c=new Consumer(stack);    Thread t1=new Thread(p);  Thread t2=new Thread(c);  t1.start();  t2.start();   }

    }

    class Producer implements Runnable{ SyncTest stack; public Producer(SyncTest s){  stack=s; }

     @Override public void run() { for(int i=0;i<20;i++){  char c=(char)(Math.random()*26+'A');  stack.push(c);  try {   Thread.sleep((int)Math.random()*300);  } catch (InterruptedException e) {   // TODO Auto-generated catch block   e.printStackTrace();  } } } }

    class Consumer implements Runnable{ SyncTest stack;

     public Consumer(SyncTest s){  stack=s; } public void run(){  for(int i=0;i<20;i++){   char c=stack.pop();   try {    Thread.sleep((int)(Math.random()*800));   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  } }}

     

     

     

    package com.cric.testThread;

    public class SyncTest { private int index=0; private char[] data=new char[6]; public synchronized void push(char c){  while(index==data.length){   try {    this.wait();   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }  this.notify();  data[index]=c;  index++;  System.out.println("produced "+c); } public synchronized char pop(){  while(index==0){   try {    this.wait();   } catch (InterruptedException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }  }  this.notify();  index--;  System.out.println("消费: "+data[index]);  return data[index]; }}


    最新回复(0)