淘宝面试题(未完 待更)

                                 淘宝面试题(Volatile)
package com.qqjx.thread;

/**
 * 淘宝面试题
 * 实现一个容器,提供两个方法,add,size
 * 写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5个时,线程2给出提示并结束
 *
 * 分析下面这个程序,能完成这个功能吗?
 * @author mashibing
 */

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class T01_WithoutVolatile {
    
    

    List lists = new ArrayList();

    public void add(Object o) {
    
    
        lists.add(o);
    }

    public int size() {
    
    
        return lists.size();
    }

    public static void main(String[] args) {
    
    
        T01_WithoutVolatile c = new T01_WithoutVolatile();

        new Thread(() -> {
    
    
            for(int i=0; i<10; i++) {
    
    
                c.add(new Object());
                System.out.println("add " + i);

                try {
    
    
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
    
    
                    e.printStackTrace();
                }
            }
        }, "t1").start();

        new Thread(() -> {
    
    
            while(true) {
    
    
                if(c.size() == 5) {
    
    
                    break;
                }
            }
            System.out.println("t2 结束");
        }, "t2").start();
    }


}

猜你喜欢

转载自blog.csdn.net/m0_52936310/article/details/113066129