我遇到了一个情况,我的多线程应用程序正在相互竞争。我有一个初始的启动方法:
public void standAloneStartup(){
try {
this.startupComms();
} catch (InterruptedException ex) {
Logger.getLogger(ThinClientEngine.class.getName()).log(Level.SEVERE, null, ex);
}
this.startupProcess();
this.requestAllProjects();
}下面是startupComms方法:
final synchronized void startupComms() throws InterruptedException{
//Listen for connections
this.tceServer = new Server(6300, this, "ThinClientEngineServer");
te.execute(tceServer);
this.tceServer.join();
Info.Info(this.tceServer.getServerName() + " is running and can recieve connections...");
//Connect to Application Server
this.appClient = new Client("localhost", 6000, this, "AppEngineClientConnection");
te.execute(appClient);
this.appClient.join();
Info.Info(this.appClient.getClientName() + " successfully connected...");
}正如您所看到的,我已经尝试过使方法synchronized,并且我也尝试join线程,以便当前不处理。从我所读到的内容来看,join方法将等待线程完成或调用notify。
启动过程中的事件顺序如下:
现在,第二步创建一个ServerConnection,但是当第三步被调用时,ServerConnection实例尚未创建,并且为null。
这一切都是被激怒的,因为我意识到我试图修复的对象流有一些问题。最后,我意识到我需要确保写和读对象方法是同步的,这就带来了一个问题,一旦我改变了这个问题。
Server和Client是从Thread扩展而来的。Server通过一个ClientConnection启动服务器套接字,其中包含一个用于侦听和接受连接的with true循环。Client启动一个ServerConnection,它也是一个线程。te是我的ThreadPoolExecutor。
在继续之前,我如何确保等待那些先前的线程?
如果你想看完整的课程,让我知道,我会张贴要求的课程。
发布于 2017-02-26 19:34:34
从javadoc到加入()
等待这个线程死掉。
所以:
this.tceServer.join();
Info.Info(this.tceServer.getServerName() + " is running and can recieve connections...");听起来是个大矛盾。您等待服务器线程到die;然后您希望它是可用的!
这就解释了为什么您的代码没有完成您期望的操作;您对A)连接()正在做什么以及B)线程子类的run()方法的行为的假设都不准确。
为了让真正帮助解决底层问题,您必须向我们展示该服务器类的代码;并且您必须解释te.execute(tceServer);到底应该做什么。好吧,不解释;但是在这里提供代码。
https://stackoverflow.com/questions/42472903
复制相似问题