我想我已經看到一些實現。其基本思想是大致
class UiThreadExecutor implements Executor {
private final Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable command) {
mHandler.post(command);
}
}
您可以通過委託它傳遞到處理程序的主線程運行在主線程什麼。
編輯:https://github.com/square/retrofit/blob/master/retrofit/src/main/java/retrofit/android/MainThreadExecutor.java例如
EDIT2:您可以配置例如像處理程序SensorManager#registerListener(..., Handler handler)
允許你這樣做。
class HandlerThreadExecutor implements Executor {
private final Handler mHandler;
public HandlerThreadExecutor(Handler optionalHandler) {
mHandler = optionalHandler != null ? optionalHandler : new Handler(Looper.getMainLooper());
}
@Override
public void execute(Runnable command) {
mHandler.post(command);
}
}
在使用當前線程的彎針的優點是,它使你明確使用的Looper
。在你的解決方案中,你可以使用任何線程調用的Looper new ExecuteOnCaller()
- 而這通常不是你以後運行代碼的線程。
我很高興知道如何在不使用Handler和Looper等Android特有的東西的情況下實現相同的效果,只需使用純Java。
Looper
,Handler
並且所有邏輯後面的消息隊列都是由大多數純Java構成的。通用解決方案的問題在於,您無法「注入」代碼以運行到線程中。該線程必須定期檢查某種類型的任務隊列以查看是否需要運行。
如果你寫這樣
new Thread(new Runnable() {
@Override
public void run() {
while (!Thread.interrupted()) {
System.out.println("Hello");
}
}
}).start();
代碼那麼有沒有辦法讓這個線程做任何事情,但始終打印「Hello」。如果你能做到這一點,就像動態插入跳轉到其他代碼到程序代碼。這會讓IMO成爲一個可怕的想法。
final BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Runnable codeToRunInThisThread = queue.take();
codeToRunInThisThread.run();
}
} catch (InterruptedException ignored) {}
}
}).start();
。另一方面是一個簡單的線程循環永遠都在排隊。該線程可以在其中執行其他任務,但您必須在代碼中添加手動檢查。
並且你可以通過
queue.put(new Runnable() {
@Override
public void run() {
System.out.println("Hello!");
}
});
這裏有沒有定義特殊的處理,但是這是一個什麼樣處理器&尺蠖在做Android的核心發送任務。 Android中的Handler
允許您定義Message
的回調,而不僅僅是Runnable
。
Executors.newCachedThreadPool()
和類似的大致相同的事情。在單個隊列中只有多個線程正在等待代碼。
進行了擴展,這個問題,是有可能做同樣的事情,但不只是UI線程,但與任何特定線程,在調用異步方法制成?
通用答案是否定的。只有當有一種方法注入代碼才能在該線程中運行。
無法理解您的問題!什麼是執行者?請詳細說明一下!謝謝 –