Waiting for event thread to finish

Post here your questions about the Java client / Android API for SFS2X

Moderators: Lapo, Bax

Post Reply
superdude
Posts: 18
Joined: 05 May 2013, 11:24

Waiting for event thread to finish

Post 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.
superdude
Posts: 18
Joined: 05 May 2013, 11:24

Re: Waiting for event thread to finish

Post 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();
		}
	}


User avatar
Lapo
Site Admin
Posts: 23438
Joined: 21 Mar 2005, 09:50
Location: Italy

Re: Waiting for event thread to finish

Post 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.
Lapo
--
gotoAndPlay()
...addicted to flash games
superdude
Posts: 18
Joined: 05 May 2013, 11:24

Re: Waiting for event thread to finish

Post 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!
Post Reply