簡體   English   中英

使用java(Threads)從方法返回值

[英]Returning Value From a Method Using java(Threads)

我是線程概念的新手,我正在努力學習....

我遇到了一種情況,我有一個方法,它返回一個學生列表......以及其他方法,使用此列表來提取學生的其他詳細信息,如ParentsName,他們參與的體育等(基於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);
       }
   }
}

我使用此鏈接 - 從Thread返回值列表為NULL。
我哪里錯了...... ???

您很可能不等待結果完成。

一個簡單的解決方案是使用ExecutorService而不是創建自己的線程池。

http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor--

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();

這給了更多選項,例如

  • 捕獲拋出的任何異常,以便您知道出了什么問題。
  • pool isDone()查看它是否已准備就緒
  • 用tiemout調用get()。
  • 有一個線程池,它重用線程或有多個線程。

你得到null因為行ArrayList<student> List=b.getStudentList(); 在您的數據庫查詢發生之前執行,因為這發生在一個單獨的線程中。

您必須等到數據庫查詢線程執行完成。 一種方法是在線程上使用join()方法。

Thread t = new Thread(new studentClass());
t.start();
t.join();

或者您可以使用Java提供的Callable接口來從線程返回值。 請參閱本文作為起點。

在代碼示例中,如果StudentClass run方法將花費幾秒鍾,您將打印為空,因為尚未設置列表。

public class MainClass
{

    public static void main(String args[]) throws Exception
{

    StudentClass b = new StudentClass();

    ExecutorService executorService = Executors.newFixedThreadPool(3);
    Future<List<Student>> studentList = executorService.submit(b);

    // When the thread completed fetching from DB, studentList will have records
    while(studentList.isDone())
    {
        System.out.println("COoolllll" + studentList.get());
    }
}
}

public class StudentClass implements Callable<List<Student>>{

private volatile List<Student> studentList;

public List<Student> getStudentList()
{
    return studentList;
}

@Override
public List<Student> call() throws Exception
{
    /**
     * studentList will fetch from DB
     */
    studentList = new ArrayList<Student>(); 
    return studentList;
}}

我認為最好有一個學生列表的全局實例,然后調用線程填充它,並有另一個bool變量來識別線程的工作是否完成或類似的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM