经典指数          
原因
1669
浏览数
0
收藏数
 

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

     举报   纠错  
 
切换
1 个答案

static List list = Collections.synchronizedList(new ArrayList());

    int size = 5;

    static int apple  = 0;

    public static void main(String[] args) throws InterruptedException {

        InputApple inputApple = new InputApple();

        OutputApple outputApple = new OutputApple();

        new Thread(inputApple).start();

        new Thread(outputApple).start();

    }

    /**

     * 放入

     * */

    private static class InputApple implements Runnable{

        @Override

        public void run() {

            while (true) {

                try {

                    Thread.sleep(new Random().nextInt(3)*900);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                if(list.size() < 5){

                    apple ++;

                    list.add(""+apple);

                    System.out.println("放入");

                }else{

                    System.out.println("已经放满");

                }

            }

        }

    }

    /**

     * 拿出

     * */

    private static class OutputApple implements Runnable{

        @Override

        public void run() {

            while (true) {

                try {

                    Thread.sleep(new Random().nextInt(3)*800);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

                if(list.size() > 0){

                    list.remove(new Random().nextInt(list.size()));

                    System.out.println("拿走");

                }else{

                    System.out.println("已经空了");

                }

            }

        }

        

    }

 
切换
撰写答案