- package fa;
- /*1.用线程模拟竞拍过程
- 创建4条线程,代表4个人,设置线程名称分别为:
- (“匿名A”,“匿名B”,“匿名C”,“匿名D”)。
- 4个人一共可以竞拍8次,每次竞拍出的价为1-100(包含1和100)的随机数,
- 每次出价需要3000ms,创建1个map集合<线程名,出价>将这四个人存入进去,出价默认为0,
- 开始竞价后将每个人每次出的价存放进去,竞拍结束后以每个人最后出价为准。
- 将竞拍价最高的线程名和成交价打印出来
- 打印格式如下:
- 匿名A以98元的价格成交*/
- import java.util.*;
- public class test1 implements Runnable{
-
- static TreeMap<String,Integer>m=new TreeMap<String,Integer>();
- static int num=0;//限制竞价次数的变量,
- //static Thread t;
- public void run(){
- while(true){
- synchronized(""){
- if(num<8){
- try {
- Thread.sleep(3000);
- jingjia();
-
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }}}}
- }
-
- public void jingjia(){
- Thread t=Thread.currentThread();
- Random r=new Random();
- int mon=r.nextInt(100)+1;
- //System.out.println(t.getName() );
- m.put(t.getName(),mon);
- num++;
- }
- public static void print1() throws InterruptedException//打印出其中出最高价的线程名,出价
- {
-
- int temp=0;String ss1;String st=null;
- Set<Map.Entry<String, Integer>> s= m.entrySet();
- //System.out.println(s);
- Iterator<Map.Entry<String, Integer>> i=s.iterator();
- while(i.hasNext()){
- Map.Entry<String,Integer>me=i.next();
- Integer v=me.getValue();
- ss1=me.getKey();
- if(v>temp){
- temp=v;
- st=ss1;
- }
- }
- System.out.println(st+"以"+temp+"元的价格成交");
-
- }
- public static void main(String[]args) throws InterruptedException{
- test1 t=new test1();
- Thread 匿名A=new Thread(t,"匿名A");
- Thread 匿名B=new Thread(t,"匿名B");
- Thread 匿名C=new Thread(t,"匿名C");
- Thread 匿名D=new Thread(t,"匿名D");
- 匿名A.start();
- 匿名B.start();
- 匿名C.start();
- 匿名D.start();
-
- Thread.sleep(30000);//使主线程休眠足够长时间,保证其他线程先完成
- System.out.println(m);
- print1();
- }
- }
复制代码 |
|