如何在Java中的现有线程中执行Callable

时间:2019-04-28 13:32:27

标签: java multithreading

我有问题。我必须创建一个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...
     }
}

有人有什么想法,解决方案等吗? 我将非常感谢您的帮助:)

0 个答案:

没有答案