设计要求: 
1. 用多线程技术实现多人过独木桥;
2. 模拟不同速度过桥;
3. 用面向对象方法设计程序。
怎么做???大神们

解决方案 »

  1.   

    只能用文字,不会用图形
    public class Bridge { private boolean occupied;
    private long length;

    public Bridge(boolean occupied, long length){
    this.occupied = occupied;
    this.length = length;
    }

    public void setOccupied(boolean o){
    this.occupied = o;
    }

    public boolean isOccupied(){
    return this.occupied;
    }

    public long getLength(){
    return this.length;
    }
    }public class Person {

    private String name;
    private int speed;

    public Person(String n, int s){
    this.name = n;
    this.speed = s;
    }

    public void crossingBridge(Bridge b){
    synchronized(b){
    try{
    while(b.isOccupied()){
    b.wait();
    }
    }catch(InterruptedException ie){

    }

    b.setOccupied(true);
    long timeElapse = b.getLength() / speed;
    try{
    Thread.sleep(timeElapse * 1000);
    b.setOccupied(false);
    b.notifyAll();
    }catch(InterruptedException ioe){
    ioe.printStackTrace();
    }
    }
    }

    public int getSpeed(){
    return this.speed;
    }

    public String getName(){
    return this.name;
    }
    }
     public class CrossingBridge implements Runnable { private Bridge bridge;
    private Person person;

    public CrossingBridge(Bridge b, Person p){
    this.bridge = b;
    this.person = p;
    }
    public void run(){
    System.out.println(person.getName() + " start crossing bridge.");
    person.crossingBridge(bridge);
    System.out.println(person.getName() + " crossed bridge.");
    }

    public static void main(String args[]){
    Bridge b = new Bridge(false,100);
    Person p1 = new Person("slow", 5);
    Person p2 = new Person("fast", 10);

    Thread t1 = new Thread(new CrossingBridge(b, p1));
    Thread t2 = new Thread(new CrossingBridge(b, p2));

    t1.start();
    t2.start();
    }
    }