package day05;
import java.util.*;
public class Dame6 {
public static void main(String[] args) {
/*用线程模拟竞拍过程
创建4条线程,代表4个人,设置线程名称分别为:(“匿名A”,“匿名B”,“匿名C”,“匿名D”)。4个人一共可以竞拍8次,
每次竞拍出的价为1-100(包含1和100)的随机数,每次出价需要3000ms,
创建1个map集合<线程名,出价>将这四个人存入进去,出价默认为0,开始竞价后将每个人每次出的价存放进去,
竞拍结束后以每个人最后出价为准。将竞拍价最高的线程名和成交价打印出来
打印格式如下:
匿名A以98元的价格成交
*/
Runnable runnable = new Runnable() {
int num=0,mapName=0;
Object ob= new Object();
Map<String, Integer> map=new HashMap<>();
@Override
public void run() {
Set<String> keys = map.keySet();
String naem=Thread.currentThread().getName();
map.put(naem,0);
while(true){
synchronized (ob){
if (num<8){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
int ran = new Random().nextInt(100)+1;
map.put(Thread.currentThread().getName(), ran);
System.out.println(Thread.currentThread().getName()+" "+ran);
num++;
}else{break;}
}
}
mapName++;
if(mapName>=4){
System.out.println();
for (String key : keys) {
//求最大数
System.out.print(key+"-->"+map.get(key)+" ");
}
}
}
};
Thread t1 = new Thread(runnable,"匿名A");
Thread t2 = new Thread(runnable,"匿名B");
Thread t3 = new Thread(runnable,"匿名C");
Thread t4 = new Thread(runnable,"匿名D");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
|
|