1

It's interesting for me how it's possible to write simple Android Handler class using only pure java to send signals from one thread to another?

I saw the source code: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/os/Handler.java

But how for example to write class (Handler class) that can send for example int value from one thread to another(not using share data(like in Android Handler?))?

4

2 回答 2

6

如果您的线程与接收消息的处理程序具有相同的方法,您可以这样做:

final Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
             // do something
    }
}

final Thread th = new Thread() {
    public void run() {
            // do something than send an integer - x in our case
            int x = 0;         
            final Message msg = Message.obtain(handler, x, null);
            handler.dispatchMessage(msg);
        }
    };
th.start();

如果您的处理程序不能直接从线程访问,则创建一个扩展 Thread 的类并将处理程序传递给该类的构造函数。

于 2012-04-13T18:18:08.520 回答
0

这就是您如何通过仅使用 Java Api 的 .

private class CustomHandler {

private final Runnable POISON = new Runnable() {
    @Override
    public void run() {}
};

private final BlockingQueue<Runnable> mQueue = new LinkedBlockingQueue<>();

public CustomHandler() {
    initWorkerThread();
}

private void initWorkerThread() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            Log.d("CustomHandler", "worker (looper) thread initialized");
            while (true) {
                Runnable runnable;
                try {
                    runnable = mQueue.take();
                } catch (InterruptedException e) {
                    return;
                }
                if (runnable == POISON) {
                    Log.d("CustomHandler", "poison data detected; stopping working thread");
                    return;
                }
                runnable.run();
            }
        }
    }).start();
}

public void stop() {
    Log.d("CustomHandler", "injecting poison data into the queue");
    mQueue.clear();
    mQueue.add(POISON);
}

public void post(Runnable job) {
    mQueue.add(job);
}
}

我想指出问题本身,即您不使用处理程序将 int 值从一个线程传递到另一个线程。处理程序用于在另一个线程中运行任务。如果要在两个线程之间共享变量,请考虑使用 volatile 关键字和原子变量。

于 2020-09-05T14:40:04.370 回答