该类OrderBook如下所示:
public class OrderBook {
private TreeMap<Double, Double> bids;
private TreeMap<Double, Double> asks;
private Entry<Double, Double> bestBid;
private Entry<Double, Double> bestAsk;
public OrderBook() {
this.bids = new TreeMap<>();
this.asks = new TreeMap<>();
}
// Getters and setters...
// Example function that modifies its variables...
public void updateBids(double bidPrice, double bidVol) {
if(this.getBids().containsKey(bidPrice)) {
if(bidVol == 0.0) {
//System.out.println("Vol. 0: " + bidPrice + " - " + bidVol);
this.getBids().remove(bidPrice);
}
else if(bidVol > 0.0) {
//System.out.println("Actualizar Vol.: " + bidPrice + " - " + bidVol);
this.getBids().replace(bidPrice, bidVol);
}
else {
//System.out.println("Error. Unexpected volume:" +
// bidPrice + " - " + vol);
}
}
else {
// ...
}
this.setBestBid(this.getBids().lastEntry());
}
}
Client 1类和Client 2类彼此不同(它们对它们的OrderBook类执行不同的写操作)并且它们是从不同的线程启动的。一个Client类看起来像这样:
public class Client1 extends WebSocketClient {
private OrderBook ob;
public Client1(URI serverURI, OrderBook ob) {
super(serverURI);
this.ob = ob;
}
// Extended class implementations...
@Override
public void onMessage(String message) {
parse(message);
}
private void parse(String msg) {
JSONObject json = new JSONObject(msg);
if(json.has("b")) {
double b = json.getDouble("b");
double a = json.getDouble("a");
double B = json.getDouble("B");
double A = json.getDouble("A");
/**
* HERE performs the modification of the OrderBook class passed in the
* constructor. I don't know if this synchronized block is needed...
*/
synchronized(this.ob) {
this.ob.setBestBid(new AbstractMap.SimpleEntry<>(bidPrice, bidVol));
this.ob.setBestAsk(new AbstractMap.SimpleEntry<>(askPrice, askVol));
}
}
}
}
问题出现在Main课堂上(在另一个线程中启动)时,我尝试读取类OrderBook正在修改的Client x类的更新实例......
Main类看起来像这样...
public class Main implements Runnable {
private OrderBook ob1;
private OrderBook ob2;
public Oportunity(OrderBook ob1, OrderBook ob2) throws URISyntaxException {
this.ob1 = ob1;
this.ob2 = ob2;
}
@Override
public void run() {
while(true) {
// PROBLEM HERE: doesn't show anything...
System.out.println(this.ob1.getLasValue());
System.out.println(this.ob2.getLasValue());
}
}
public static void main(String[] args) throws Throwable {
OrderBook ob1 = new OrderBook();
OrderBook ob2 = new OrderBook();
Thread client1 = new Thread(new Client1(new URI("..."), ob1));
Thread client2 = new Thread(new Client2(new URI("..."), ob2));
Thread m = new Thread(new Main(ob1, ob2));
client1.start();
client2.start();
m.start();
}
}
问题:
- 我怎样才能始终如一地访问两个实例的最后更新值
OrderBook? - 另外,是否可以显示写操作优先于读操作?
