• 阿里巴巴实习生笔试题目


    用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();
    			}
    		}
    	}
    }
    

      

  • 相关阅读:
    『Nltk』常用方法
    『Kaggle』分类任务_决策树&集成模型&DataFrame向量化操作
    『Pandas』数据读取&DataFrame切片
    『TensotFlow』RNN中文文本_下_暨研究生开学感想
    『Scrapy』爬取斗鱼主播头像
    『Scrapy』爬取腾讯招聘网站
    『TensorFlow』梯度优化相关
    『Scrapy』终端调用&选择器方法
    『Scrapy』全流程爬虫demo
    使用VS2013、TFS2013和Git进行分布式团队协作
  • 原文地址:https://www.cnblogs.com/fangying7/p/4741726.html
Copyright © 2020-2023  润新知