Call the listener method from the workflow, but run it on the thread that added the listener

I am writing a TCP server class that I want to be standalone. That is, applications using this class do not have to worry about internal workflows. The TCP server class has a start () method, and I want to be able to call listener methods on the same thread called start () (in normal use, the main thread). This is probably better explained by the code:

public class ProblemExample { private Listener mListener; public ProblemExample() { mListener = new Listener() { @Override public void fireListener() { System.out.println(Thread.currentThread().getName()); } }; } public void start() { mListener.fireListener(); // "main" is printed new Thread(new Worker()).start(); } public interface Listener { public void fireListener(); } private class Worker implements Runnable { @Override public void run() { /* Assuming the listener is being used for status updates while * the thread is running, I'd like to fire the listener on the * same thread that called start(). Essentially, the thread that * starts the operation doesn't need to know or care about the * internal thread. */ mListener.fireListener(); // "Thread-0" is printed } } } 

I tried looking for this, but I'm not sure what to look for. The best I have found is SwingWorker , it seems like this, but I can’t find out how to do it.

Can anyone shed some light?

+4
source share
1 answer

What you are asking for is theoretically impossible without explicit collaboration with the client thread (one called start() ). Just stop thinking about it: the main thread is always busy running specific code in a specific method. The full call stack is for the current call. Now you would like to abort this and start executing the listener code from the very beginning.

The way Swing achieves this is to start the main event loop in Thread Dispatch Thread. In this loop, you can imagine that Runnable instances are pulled from the queue and their run methods are called in turn. Only when one run method returns can the next be called.

This is what you need to develop for your business, but I'm not sure if you had anything like that. The only alternative is explicit support for listener methods executed in the external thread.

+1
source

All Articles