`

独木桥问题多线程--java编程

    博客分类:
  • JAVA
 
阅读更多

public class Pedestrian implements Runnable{  static int an,bn;  static int count;
 boolean as=false,bs=false;
 public static void main(String [] args) {   Pedestrian p=new Pedestrian();  }
 public Pedestrian() {
  Scanner inputa=new Scanner(System.in);
  System.out.println("请输入在a方向的行人数目:");   an=inputa.nextInt();
  Scanner inputb=new Scanner(System.in);
  System.out.println("请输入在b方向的行人数目:");   bn=inputb.nextInt();   count=an+bn;
  while(count>0) {
    thread1 a=new thread1(this,"a");           a.start(); 
          thread1 b=new thread1(this,"b");           b.start();       }     }
 class thread1 extends Thread {
  public thread1(Runnable r, String name) {    super(r, name);     }    }
 public synchronized void run(){
  thread1 t=(thread1)Thread.currentThread();   if (t.getName().equalsIgnoreCase("a") && an>0 && bs==false) {
   as=true;
   int i=(int)(Math.random()*100%an);    if(i<an) i=i+1;    an=an-i;
   System.out.println("a方向上有"+i+"人过桥!"+" 还剩人数为:"+an);
   int n;
   n=(int)(Math.random()*2);
   System.out.println("a方向上新增人数:"+n+"    现要过桥人数为:"+(an+n));    an=an+n;    if(an==0) {
    System.out.println("a方向上的人已全过桥!");


  
 


   }
   as=false;             }   if (t.getName().equalsIgnoreCase("b") && bn>0 && as==false) {
   bs=true;
   int j=(int)(Math.random()*100%bn);    if(j<bn) j=j+1;    bn=bn-j;
   System.out.println("b方向上有"+j+"人过桥!"+"还剩人数为:"+bn);
   int m;
   m=(int)(Math.random()*2);
   System.out.println("b方向上新增人数:"+m+"    现要过桥人数为:"+(bn+m));    bn=bn+m;    if(bn==0) {
    System.out.println("b方向上的已全过桥!");    }
   bs=false;    }
  count=an+bn;  } }

 
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics