我是线程概念的新手,我正在尝试学习......
我遇到过一种情况,我 有一个返回学生列表的方法...以及使用此列表的其他方法 拉取学生的其他详细信息,例如 parent 姓名、他们参加过的运动 等(基于StudentID)..我尝试使用以下代码返回一个列表,但似乎不起作用:(
import java.util.ArrayList;
public class studentClass implements Runnable
{
private volatile List<Student> studentList;
@Override
public void run()
{
studentList = "Mysql Query which is returning StudentList(StudentID,StudentName etc)";
}
public List<Student> getStudentList()
{
return studentList;
}
}
public class mainClass
{
public static void main(String args[])
{
StudentClass b = new StudentClass();
new Thread(b).start();
// ...
List<Student> list = b.getStudentList();
for(StudentClass sc : b)
{
System.out.println(sc);
}
}
}
我使用了这个链接 - Returning value from Thread
该列表为 NULL。
我哪里错了......???
最佳答案
您很可能没有等待结果完成。
一个简单的解决方案是使用 ExecutorService 而不是创建自己的线程池。
ExecutorService es = Executors.newSingleThreadExecutor();
Future<List<Student>> future = es.submit(new Callable<List<Student>>() {
public List<Student> call() throws Exception {
// do some work to get this list
}
};
// do something
// wait for the result.
List<Student> list = future.get();
这提供了更多选择,例如
- 捕获抛出的任何异常,以便您知道出了什么问题。
- 池
isDone()
查看是否准备就绪 - 使用 tiemout 调用 get()。
- 拥有一个可重复使用线程或拥有多个线程的线程池。
关于java - 使用 java(Threads) 从方法返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24751706/