我有问题。我必须创建一个Scheduler.java
文件,该文件包含带有两个参数的delegate
方法:Thread thread, Callable<T> callable
。可调用必须在参数中使用的线程中执行,并且方法delegate
也需要从callable.call()
方法返回结果。
我尝试使用ExecutorService
,但我不知道如何使用现有线程来运行其他任务。
我也有代码,Scheduler.java
应该通过:
final Scheduler s = new Scheduler();
final Thread[] threads = new Thread[2];
Thread lolek = new Thread() {
public void run() {
try {
System.out.println(s.delegate(threads[1], new Callable<String>() {
public String call() { return "Pat a " + Thread.currentThread(); }
}));
} catch (Exception e) {
e.printStackTrace();
}
}
public String toString() { return "Lolek"; }
};
Thread mat = new Thread() {
public void run() {
try {
System.out.println(s.delegate(threads[0], new Callable<String>() {
public String call() { return "Bolek i " + Thread.currentThread(); }
}));
} catch (Exception e) {
e.printStackTrace();
}
}
public String toString() { return "Mat"; }
};
threads[0] = lolek;
threads[1] = mat;
for (Thread t : threads) t.start();
然后我创建了Scheduler.java
:
public class Scheduler {
Object value = "";
public Scheduler() { }
public synchronized <T> T delegate(Thread thread, Callable<T> callable) {
// magic here...
}
}
有人有什么想法,解决方案等吗? 我将非常感谢您的帮助:)