Page 1 of 1
Waiting for event thread to finish
Posted: 28 Jun 2013, 22:59
by superdude
When connecting to the server, I'd like the main thread that calls SmartFox.connect() to wait for the other thread that gets started to finish its work before the main thread continues.
I can't quite figure out how to do this. Is there a way to reference this thread somehow and do a Thread.join() with it? Or some other more clever way? Thanks.
Re: Waiting for event thread to finish
Posted: 30 Jun 2013, 13:22
by superdude
I ended up doing it like this. Works well!
Code: Select all
@Override
public boolean connect(String server, int port) {
connectSuccess = false; //Global variable
threadDone = false; //Global variable
sfs.connect(server, port);
//Wait for SFS thread to attempt the connection
doneLock = new Object();
synchronized (doneLock){
while (!threadDone){
try {
doneLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return connectSuccess;
}
@Override
public void dispatch(BaseEvent event) throws SFSException {
if (event.getType().equalsIgnoreCase(SFSEvent.CONNECTION)) {
if (event.getArguments().get("success").equals(true)) {
connectSuccess = true;
} else {
connectSuccess = false;
}
}
//When another thread is waiting, let it know
synchronized (doneLock){
threadDone = true;
doneLock.notifyAll();
}
}
Re: Waiting for event thread to finish
Posted: 30 Jun 2013, 16:41
by Lapo
You mean you want your main thread to wait until the connection thread is done?
We designed the API in the opposite direction, in other words not to lock the main thread

Everything is asynchronous and even based in our API.
I don't understand why you would do that, your main thread will either go back doing UI work or just finish, in case there's no more work for it do. In any case the application will keep running with the other threads.
Re: Waiting for event thread to finish
Posted: 30 Jun 2013, 23:54
by superdude
There were some things I wasn't able to do directly from the connection thread with Libgdx due to OpenGL. Waiting for the thread to finish was one solution, but I also eventually found a way to post runnables from the connection thread to the main thread, so that worked even better. Either way, problem is solved!