java基础之多线程


    
    public static void main(String[] args) {
        //创建四条线程
        Thread t1 =new GivePrice();
        t1.setName("匿名A");
        t1.start();
        Thread t2 =new GivePrice();
        t2.setName("匿名B");
        t2.start();
        Thread t3 =new GivePrice();
        t3.setName("匿名C");
        t3.start();
        Thread t4 =new GivePrice();
        t4.setName("匿名D");
        t4.start();
        
        
    }

}
//创建Thread的子类
class GivePrice extends Thread{
    private static int num =8;
    int price = (int) (Math.random()*100+1);
    Map map = new HashMap();
    public void run() {
        while(true){
            synchronized(GivePrice.class){
                if(num == 0){
                    String k = getMax(map);
                    if(getName().equals(k)){
                        System.out.println(k+"以"+map.get(k)+"元的价格成交");
                    }
                    break;
                }
                try {
                    num--;
                    map.put(getName(), price);
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    
                    e.printStackTrace();
                }
            }
        }
        
        
        
    }
//找出map中存储的最高价,循环遍历:用增强for
    private  String getMax(Map map) {
        int max = 0;
        String k = "";
        for ( String key: map.keySet()) {
            int m= map.get(key);
            if(max < m){
                int temp = max;
                max = m;
                m = temp;
                k=key;
            }
        }
        System.out.println(k);
        return k;
        
    }
}

原文地址:https://www.cnblogs.com/fanfusuzi/p/6853102.html