无论如何,是否可以在其中调用 A 类调用 notify(),从后台运行的线程中唤醒 wait() 上的线程以获得该对象的锁?
谢谢。
编辑:
请忽略不必要的代码。我想向您展示我是如何真正实现它的。
Messenger 是一个序列化的对象。
一个线程“ServerHandler”将调用
bufferImpObject.put(<Messenger Obj>, <ServerHandler instance>, <socket instance>)
public class BufferImp {
private Messenger[] requests;
public static int req_size;
public static int req_count;
Socket s;
Messenger msg;
InputStream is;
ObjectInputStream ois;
OutputStream os;
ObjectOutputStream oos;
public BufferImp(int size) {
this.req_size = size;
this.req_count = 0;
requests = new Messenger[size];
}
class CheckWaitThread extends Thread{
Thread t;
String s;
Socket incoming_socket;
CheckWaitThread(String s, Thread t, Socket incoming_socket){
this.t = t;
this.s = s;
this.incoming_socket = incoming_socket;
}
@Override
public void run(){
try {
// I want to keep on checking till slots are FREE
// IF FREE, call notify() of BufferImp to get back WAITING (inactive) ServerHandler thread
if(t.getState().equals(State.WAITING)){
os = incoming_socket.getOutputStream();
AppendableObjectOutputStream oosa = new AppendableObjectOutputStream(os);
oosa.writeObject(new Messenger("bufferFull", null, "true"));
}
t.join();
} catch (IOException ex) {
Logger.getLogger(BufferImp.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(BufferImp.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
// insert incoming Message objects into "requests" queue
public synchronized boolean put(Messenger o, Thread t, Socket s) throws InterruptedException {
while(req_size == req_count) {
CheckWaitThread cw = new CheckWaitThread("<----------CheckWaitThread----------->", t, s);
cw.start();
wait();
}
// these parts need to be executed when notify() is called.
requests[cur_req_in] = o;
cur_req_in = (cur_req_in + 1) % req_size;
req_count++;
notifyAll();
Messenger msg = (Messenger) o;
return true;
}
}