我创建了2个线程。我需要从一个线程向另一个线程提交可运行对象,然后在另一个线程中执行它。有可能吗?
编辑:实际上,我需要使用主线程,而不仅仅是另一个。因此,无法使用ExecutorService。
编辑:有解决此问题的方法:Running code on the main thread from a secondary thread?。
我已在示例下方发布:
public class SomeClass {
private static Thread thread;
private static Thread another_thread;
public static void main(String[] args) {
thread = new Thread(() -> {
//do something
Runnable runnable = () -> {
//do something
};
//submit runnable to another_thread
//do something else while the Runnable runnable is being executed in another_thread
});
another_thread = new Thread(() -> {
//do something
});
another_thread.start();
thread.start();
}
}
答案 0 :(得分:1)
这是您通常想要做的:
class YourClass {
public static void main(String[] args) {
ExecutorService executor1 = Executors.newSingleThreadExecutor();
ExecutorService executor2 = Executors.newSingleThreadExecutor();
Runnable run1 = () -> {
Runnable run2 = createRunnable();
// submit in second thread
executor2.submit(run2);
}
// submit in first thread
executor1.submit(run1);
}