多线程之模拟多人过山洞

来源:互联网 发布:从零开始学java.epub 编辑:程序博客网 时间:2024/04/29 03:23

 编写多线程程序,模拟多个人通过一个山洞。这个山洞每次只能通过一个人,每个人通过山洞的时间为2秒(sleep)。随机生成10个人,都要通过此山洞,用随机值对应的字符串表示人名,打印输出每次通过山洞的人名。提示:利用线程同步机制,过山洞用一条输出语句表示,该输出语句打印输出当前过山洞的人名,每个人过山洞对应一个线程,哪个线程执行这条输出语句,就表示哪个人过山洞。

import java.util.LinkedHashSet;import java.util.Set;public class GuoShanDong implements Runnable{ private static int wait=0;       public void run() {                     wait= wait+2000;                            try                {                    Thread.sleep(wait);                }            catch (InterruptedException e)                {                    e.printStackTrace();                }            System.out.println(Thread.currentThread().getName() +" 过山洞");}public static void main(String[] args) {   String ary[] ={"A","B","C","D","E","F","G","H","I","J"};                  GuoShanDong gsd = new GuoShanDong();                   Set<Integer> set=new LinkedHashSet<Integer>();       while(true){       if(set.size() == 10){       break;       }                //乱序排列(随机)       int a=(int) (Math.random()*10);           set.add(a);       }              for(int b:set){          Thread th = new Thread(gsd, ary[b]);          th.start();       }                        }}


阅读全文
0 0