我在里面有Socket的线程。当soket收到一些数据时,我需要触发事件(使用我的sublassed EventObject)。从主线程(到某些列表?)添加事件侦听器。这样好吗?
Pseudocode:
public class SocketThread extends Thread{
private Socket socket;
private MyEventListener eventListener;
public SocketThread(Socket socket, MyEventListener eventListener) {
this.socket=socket;
this.eventListener=eventListener;
}
public void run() {
get socket input stream...
get socket output stream...
when data received, call process(data)
}
void process(data){
synchronized(this){
myEvent event=new MyEvent(data);
eventListener.fireSomeEvent(myEvent );
}
}
// main thread
ServerSocket serverSocket=new ServerSocket(host,port);
Socket socket= serverSocket.accept();
ClientThread cthr = new SocketThread (sckt,new MyEventListener(){
void fireSomeEvent(MyEvent event){
//some code
}
});
答案 0 :(得分:0)
这似乎完全没问题。只要您不更改eventListener
,就不会出现并发问题。但请注意,fireSomeEvent()
将从SocketThread
运行。如果你在那里做一些非线程安全的事情,你可能会(会)遇到问题。这就是你需要某种同步的地方。