标签:
今天参加了阿里2015校招实习生的笔试。
选择题部分确实有水平,由于基础一般再加上没做准备,打得一塌糊涂,目测已经阵亡了,不过附加题的最后一个还是很基础的,关于java的多线程中的生产者和消费者的问题,在此感谢@绝影。
题目:
有个篮子,一个人不停地往里面放苹果,另一个不停地从里面拿出来苹果,篮子最多能放5个苹果,苹果数量无限。用Java模拟实现。
实现过程:
主类:
class ProducerConsumer { public static void main(String[] args) { StackBasket s = new StackBasket(); Producer p = new Producer(s); Consumer c = new Consumer(s); Thread tp = new Thread(p); Thread tc = new Thread(c); tp.start(); tc.start(); } }
class StackBasket { Apple sm[] = new Apple[5]; int index = 0; public synchronized void push(Apple m){ try{ while(index == sm.length){ System.out.println("放满了"); this.wait(); } this.notify(); }catch(InterruptedException e){ e.printStackTrace(); }catch(IllegalMonitorStateException e){ e.printStackTrace(); } sm[index] = m; index++; System.out.println("放置:" + m + " 共" + index + "个苹果"); } public synchronized Apple pop(){ try{ while(index == 0){ System.out.println("拿光了"); this.wait(); } }catch(InterruptedException e){ e.printStackTrace(); }catch(IllegalMonitorStateException e){ e.printStackTrace(); } index--; System.out.println("放了:" + sm[index] + " 共" + index + "个苹果"); return sm[index]; } }
class Producer implements Runnable { StackBasket ss = new StackBasket(); Producer(StackBasket ss){ this.ss = ss; } public void run(){ for(int i = 0;i < 100;i++){ Apple m = new Apple(i); ss.push(m); try{ Thread.sleep((int)(Math.random()*500)); }catch(InterruptedException e){ e.printStackTrace(); } } } }消费者(拿苹果):
class Consumer implements Runnable { StackBasket ss = new StackBasket(); Consumer(StackBasket ss){ this.ss = ss; } public void run(){ for(int i = 0;i < 100;i++){ Apple m = ss.pop(); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){ e.printStackTrace(); } } } }
class Apple { private int id; Apple(int id){ this.id = id; } public String toString(){ return "Apple:" + id; } }
标签:
原文地址:http://blog.csdn.net/tryitboy/article/details/44838819