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(iSystem.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(jSystem.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;  } }


版权声明:本文为weixin_33532301原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。