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

      

  • 相关阅读:
    固定执行计划-SQL PROFILE手工绑定
    其他典型的执行计划
    oracle-常见的执行计划(一)
    DBMS_XPLAN详细说明
    sql-查看执行计划的方法
    CBO基础概念
    webpack生产环境保留某些console.log
    提升webpack构建速度(二)
    提升webpack构建速度(一)
    【译文】更有效的调试webpack在构建时出现的错误
  • 原文地址:https://www.cnblogs.com/fangying7/p/4741726.html
Copyright © 2011-2022 走看看