Java 如何使用共享资源与其他线程通信?

Java 如何使用共享资源与其他线程通信?,java,multithreading,oop,Java,Multithreading,Oop,有一个拍卖服务器,它接受客户机,并为每个套接字连接创建一个新线程来服务客户机。每个线程都有自己的协议。服务器只有一个拍卖对象实例拍卖对象持有地块对象列表拍卖对象作为参数传递给客户端线程协议必须有一种方式来出价并以某种方式通知所有客户端线程。makeBid方法存在于Lot中,它将标书放入标书列表中。下一步是以makeBid方法通知所有客户端线程。这样做的最佳实践是什么? 我试图在线程中使用一个字段(MSG)来保存消息。线程检查是否!MSG.isEmpty()处于run()状态时。如果!MSG.i

有一个拍卖服务器,它接受客户机,并为每个套接字连接创建一个新线程来服务客户机。每个线程都有自己的协议。服务器只有一个拍卖对象实例<代码>拍卖对象持有
地块
对象列表<代码>拍卖对象作为参数传递给客户端线程<代码>协议必须有一种方式来出价并以某种方式通知所有客户端线程。
makeBid
方法存在于
Lot
中,它将标书放入标书列表中。下一步是以
makeBid
方法通知所有客户端线程。这样做的最佳实践是什么?

我试图在线程中使用一个字段(MSG)来保存消息。线程检查是否
!MSG.isEmpty()
处于
run()
状态时。如果
!MSG.isEmpty()
然后
ClientThread
将此
MSG
打印到套接字。我认为有更好的解决办法



最好使用此对象同步“makeBid”方法。然后调用notifyAll方法


在makeBid结束时。

您可以创建一个订阅设计,每当客户端对某个地块进行出价时,该订阅设计将调用
lotUpdated()
方法。每个
ClientThread
都会订阅它想要通知的
Lots

public class Lot {
  private List<ClientThread> clients = new ArrayList<ClientThread>();
  private List<Integer> bids = new ArrayList<Integer>();

  public synchronized void subscribe(ClientThread t){
    clients.add(t);
  }

  public synchronized void unsubscribe(ClientThread t){
    clients.remove(t);
  }

  public synchronized void makeBid(int i){
    bids.add(i);
    for (ClientThread client : clients){
      client.lotUpdated(this);
    }
  }
}

public ClientThread {
  public void lotUpdated(Lot lot){
    //called when someone places a bid on a Lot that this client subscribed to
    out.println("Lot updated");
  }
}
公共类地块{
private List clients=new ArrayList();
私有列表出价=新的ArrayList();
公共同步无效订阅(客户端线程t){
添加(t);
}
公共同步作废取消订阅(客户端线程t){
删除(t);
}
公共投标(int i){
投标书。添加(i);
for(客户端线程客户端:客户端){
client.lotUpdated(this);
}
}
}
公共客户端线程{
已更新公共无效地块(地块){
//当有人对该客户订阅的地块出价时调用
out.println(“批次更新”);
}
}

有什么特别的原因不能让线程在投标消息的
阻塞队列上等待吗?这是一个好主意。我更喜欢一个能通知所有客户的观察员。所有客户端都需要在observer上注册。最好只有一个实例,比如服务器对象。(使用观察者扩展服务器)。[link]我是否会遇到ClientThread从用户字符串clientCommand=in.readLine()等待套接字输入的问题;并且在用户发送消息之前不能执行“lotUpdated”?不,这不应该是个问题。将会发生的情况是,
lotUpdated()。
public class Lot {
  private List<ClientThread> clients = new ArrayList<ClientThread>();
  private List<Integer> bids = new ArrayList<Integer>();

  public synchronized void subscribe(ClientThread t){
    clients.add(t);
  }

  public synchronized void unsubscribe(ClientThread t){
    clients.remove(t);
  }

  public synchronized void makeBid(int i){
    bids.add(i);
    for (ClientThread client : clients){
      client.lotUpdated(this);
    }
  }
}

public ClientThread {
  public void lotUpdated(Lot lot){
    //called when someone places a bid on a Lot that this client subscribed to
    out.println("Lot updated");
  }
}