自己完結型にしたい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がこれを行うように見えることですが、方法がわかりません。
誰でも光を当てることができますか?