zoukankan      html  css  js  c++  java
  • 阿里巴巴实习生笔试题目

    用Java代码模拟实现:一个人不断往箱子里放苹果,另一个人不断从箱子里取苹果,箱子只能放5个苹果,苹果数量无限。要求不使用Java.util.concurrent包中的类。

    package fangying;
    
    import java.util.ArrayList;
    import java.util.Random;
    
    public class AppleThreadDemo {
    	public static void main(String[] args) {
    		ArrayList<Apple> al = new ArrayList<Apple>();
    		AppleProducer ap = new AppleProducer(al);
    		AppleConsumer ac = new AppleConsumer(al);
    		new Thread(ap).start();
    		new Thread(ac).start();
    	}
    }
    
    class Apple {
    	private int id;
    
    	public Apple(int id) {
    		this.id = id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public int getId() {
    		return this.id;
    	}
    
    	public String toString() {
    		return "Apple " + id;
    	}
    }
    
    class AppleProducer implements Runnable {
    	private ArrayList<Apple> al;
    
    	public AppleProducer(ArrayList<Apple> al) {
    		this.al = al;
    	}
    
    	@Override
    	public void run() {
    		while (true) {
    			try {
    				Thread.sleep(new Random().nextInt(3) * 1000);
    				synchronized (this.al) {
    					if (al.size() < 5) {
    						Apple apple = new Apple(al.size() + 1);
    						al.add(apple);
    						System.out.println("放入苹果:" + apple);
    					} else {
    						System.out.println("箱子已满!");
    					}
    				}
    			} catch (InterruptedException ie) {
    				ie.printStackTrace();
    			}
    		}
    	}
    
    }
    
    class AppleConsumer implements Runnable {
    	private ArrayList<Apple> al;
    
    	public AppleConsumer(ArrayList<Apple> al) {
    		this.al = al;
    	}
    
    	@Override
    	public void run() {
    		while (true) {
    			try {
    				Thread.sleep(new Random().nextInt(2) * 1000);
    				synchronized (this.al) {
    					if (al.size() > 0) {
    						Apple ret = al.remove(al.size()-1);
    						System.out.println("拿走苹果"+ret);
    					} else {
    						System.out.println("盒子为空!");
    					}
    				}
    			} catch (InterruptedException ie) {
    				ie.printStackTrace();
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    C++ string 实现大整数相加减
    HDU2489 Minimal Ratio Tree 【DFS】+【最小生成树Prim】
    Quick-Cocos2d3.2RC1在Code IDE中实现代码提示
    Codeforces 558C Amr and Chemistry
    Linux编程---进程通信
    HDU 5371 Hotaru&#39;s problem(Manacher算法+贪心)
    微社区
    创业忌讳
    微信公众平台开发(82) 天气预报
    天气预报接口
  • 原文地址:https://www.cnblogs.com/fangying7/p/4741726.html
Copyright © 2011-2022 走看看