独木桥问题多线程--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;  } }

 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值