我正在编写一个我想要自包含的 TCP 服务器类。也就是说,使用此类的应用程序无需担心内部工作线程。TCP 服务器类有一个 start() 方法,我希望能够在调用 start() 的同一线程上调用侦听器的方法(在正常使用情况下,主线程)。这可能用代码更好地解释:
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
}
}
}
我试过搜索这个,但我不确定要搜索什么。我发现最好的是SwingWorker似乎可以做到这一点,但我不知道怎么做。
任何人都可以解释一下吗?