有一个南北向的桥,只能容纳一个人,现桥的两边分别有10人和12人,编制一个多线程序让这些人到达对岸,每个人用一个线程表示,桥为共享资源。在过桥的过程中显示谁在过桥及其走向。

package cn.thread;

public class Through_out_bridge {

    public static void main(String[] args) {
 Bridge b = Bridge.getInstance();//实例化桥
 //实例化左端9个人,此时所有人都不能过桥,桥的可以状态标志为不可以用
 for (int i = 1; i <= 9; i++) {
     Thread t = new Thread(new Person(false, i, b));
     t.start();
 }
 //实例化右端12个人,此时所有人都不能过桥,桥的可以状态标志为不可以用
 for( int i=1 ;i<=12;i++)
 {
     Thread t = new Thread(new Person(true,i,b));
     t.start();
 }
 //桥的可用状态给左端第10个人,可以自定义给谁
 b.state = true;
 Thread t = new Thread(new Person(false, 10, b));
    }

}

class Person implements Runnable {

    public Bridge bridge;//桥
    private String hand;//在桥哪一端
    int No;//序号

    public Person(boolean side, int i, Bridge bridge) {

 this.No = i;
 this.bridge = bridge;
 if(bridge.state)
 {
     System.out.println(i+"已经过桥。");
 }
 if (side) {
     this.hand = new String("右");
 } else {
     this.hand = new String("左");
 }
    }

    //过桥方法
    public synchronized void through() throws InterruptedException {

 if (bridge.state) {
     System.out.println(hand+"边第"+No + "在过桥");
     bridge.open( No);
 } else {
     bridge.lock(No);
    
 }
    }

    public void run() {
 try {
     Thread.sleep(1000);
//     System.out.println(No+hand+" 边已经过桥!");
     through();
 } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
 }
    }
}

class Bridge {
    //可用状态判断true:可用
    public boolean state = false;
    //自行实例化
    public static Bridge getInstance() {
 return new Bridge();
    }

    public synchronized void open(int i) throws InterruptedException {
 if (state) {
     Thread.sleep(1000);
     this.state=true;
     notify();
 }
    }

    public synchronized void lock(int i) throws InterruptedException {
 if (!state) {
     this.state=false;
     System.out.println(i + " 在等待.");
     wait();
 }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值