java - 在 Java 中为线程添加额外的方法?

标签 java multithreading algorithm concurrency

我以为我可以通过尝试这样的事情来做到这一点,但它不起作用:

Thread[] threads = new Thread[myNumThreads];
for (int i=0; i<myNumThreads; i++) {
    threads[i] = new Thread () {
        @Override
        public void run() {
        <Code to do when running>
        }

        //CODE I TRIED TO ADD:
        public boolean getValue(){
            return true;
        }

    };
}

基本上,我不想调用 join() 来结束线程,而是想要一种方法让线程做某事并在仍在运行时将一些数据返回给 main 方法。

最佳答案

当您运行代码时,它始终使用当前线程。如果代码附加到另一个线程对象,例如线程.join();在后台线程运行时,它仍然是当前线程等待。

让另一个线程工作的最简单方法是使用 ExecutorService

ExecutorService es = Executors.newFixedThreadPool(myNumThreads);

List<Future<ResultType>> futures = new ArrayList<>();
for (int i = 0; i < myNumThreads; i++) {
    futures.add(es.submit(new Callable<Result>() {
        public ResultType call() {
            // do something
            return result;
        }
    });
}
// do something while the thread task executes
for (Future<ResultType> future: futures) {
    ResultType result = future.get();
}
// when finished with the pool
es.shutdown();

关于java - 在 Java 中为线程添加额外的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27600800/

相关文章:

java - 如何累积考试成绩?

java - 在 Java 中使用 JaCop 优化函数

c - 在线程中使用时,recvfrom() 对于 RAW 套接字返回 -1?

c - 求冒泡排序的时间复杂度?

java - 仅当匹配阈值字节时才在映射中填充字符串值

java - 如何让tomcat 5.5支持servlet 3.0?

java - 打开Jar内的.Class文件并对其进行修改

windows - Cocoa、Windows 和线程?

c# - WPF - 尝试在任务中打开一个新窗口但收到 "The calling thread must be STA exception"

c++ - 递归后序遍历释放二叉树节点