生产者消费者问题
生产者类:
package luojing; public class producer implements Runnable { private box ss; public producer(box ss) { this.ss=ss; } public void run() { char c; for(int i=0;i<10;i++) { c=(char)(Math.random()*26+'A'); ss.put(c); try { Thread.sleep((int)(Math.random()*300)); } catch(InterruptedException e) { e.printStackTrace(); } } } }
package luojing; public class consumer implements Runnable { private box ss; public consumer(box ss) { this.ss=ss; } public void run() { for(int i=0;i<10;i++) { try { ss.get(); Thread.sleep((int)(Math.random()*500)); } catch(InterruptedException e) { e.printStackTrace(); } } } }
容器类:
package luojing; import java.util.ArrayList; import java.util.List; public class box { private List<Character> buffer = new ArrayList<Character>(); public synchronized void get() { while(buffer.size()==0) { try { System.out.println("仓库为空 "+Thread.currentThread().getName()+"正在等待......"); this.wait(); } catch(InterruptedException e) { e.printStackTrace(); } } Character c=((Character)buffer.get(buffer.size()-1)).charValue(); buffer.remove(buffer.size()-1); System.out.println(Thread.currentThread().getName()+" 消费产品:"+c); this.notify(); } public synchronized void put(char c) { while(buffer.size()>=5) { try { System.out.println("仓库已满 "+Thread.currentThread().getName()+"正在等待......."); this.wait(); } catch(InterruptedException e) { e.printStackTrace(); } } Character character=new Character(c); System.out.println(Thread.currentThread().getName()+" 生产产品"+c); buffer.add(character); this.notify(); } }
主类:
package luojing; public class mainClass { public static void main(String[] args) { box ss=new box(); producer p1=new producer(ss); Thread pThread1=new Thread(p1); pThread1.setName("生产者1"); pThread1.start(); producer p2=new producer(ss); Thread pThread2=new Thread(p2); pThread2.setName("生产者2"); pThread2.start(); consumer c1=new consumer(ss); Thread cThread1=new Thread(c1); cThread1.setName("消费者1"); cThread1.start(); consumer c2=new consumer(ss); Thread cThread2=new Thread(c2); cThread2.setName("消费者2"); cThread2.start(); } }