繁体   English   中英

多个线程在同一个对象上工作

[英]Multiple threads working on the same object

我有一个POJO BusStop,上面有公交车站的名称以及那里有多少名乘客。

public class BusStop{
    private String name;
    private Integer passengers;
    //setters getters constructor
    public void removePassengers(Integer i){
        synchronized(passengers){
             this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
        }
    }

    public void increasePassengers(Integer i){
        synchronized(passengers){
             this.passengers = this.passengers + i;
        }
    }
}

还有一个对象BusRide,其中包含源BusStop,目标BusStop以及该乘车中当前有多少乘客。

public class BusRide implements Runnable{

    private BusStop source;
    private BusStop destination
    private Integer passengers;

    public BusRide(BusStop src, BusStop dest){
        this.source = src;
        this.destination = dest;
    }
    //setters getters

    @Override
    public void run(){
        setPassengers(15);
        this.source.removePassengers(15);
        setPassengers(0);
        this.destination.increasePassengers(15);
    }
}

主班:

public class Main{

    public static void main(String[] args){
            BusStop a = new BusStop("Bus-stop 1", 50);
            BusStop b = new BusStop("Bus-stop 2", 45);
            BusStop c = new BusStop("Bus-stop 3", 62);

            Thread t1 = new Thread(new BusRide(a,b));
            Thread t2 = new Thread(new BusRide(a,c));
    }

}

在我的主类中,我想创建2个BusRide线程,这些线程将随机从源BusStop到目标BusStop乘坐乘客。 但是我希望BusRide线程从我给他们的对象中带走乘客,但是他们却拥有自己的BusStop对象实例。 那么,如何使两个线程在我赋予它们的同一BusStop对象上运行?

public void removePassengers(Integer i){
    synchronized(passengers){
         this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
    }
}

public void increasePassengers(Integer i){
    synchronized(passengers){
         this.passengers = this.passengers + i;
    }
}

以上是错误的。 它应该是

public synchronized void removePassengers(Integer i){
    this.passengers = this.passengers - i; // right now I allow them to go below zero for the sake of just testing threads;
}

public synchronized void increasePassengers(Integer i){
    this.passengers = this.passengers + i;
}

确实,您正在对一个乘客进行同步,但是将乘客分配给同步块内的另一个值,从本质上来说,两个线程可以同时调用方法。 如果将其用作锁,请始终使变量为final

请尝试这个。 线程未启动。

/ ** * * /包com.philips.webcms.foundation.catalog.products.utils.test;

/ ** * @author AV262488 * /公共类ThreadTest {

/**
 * @param args
 */
public static void main(String[] args)
{
    BusStop a = new BusStop("Bus-stop 1", 50);
    BusStop b = new BusStop("Bus-stop 2", 45);
    BusStop c = new BusStop("Bus-stop 3", 62);

    Thread t1 = new Thread(new BusRide(a, b));
    Thread t2 = new Thread(new BusRide(a, c));
    t1.start();
    t2.start();

    System.out.println(a.getPassengers());

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM