我以为我可以通过尝试这样的事情来做到这一点,但它不起作用:
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/