Java有线程返回主线程的东西

时间:2012-08-18 20:17:05

标签: java multithreading return

我坚持不懈,似乎无法想到解决方案。我有一个名为dbSelect的函数,然后创建一个线程来运行MySQL查询并获得ResultSet,但是我需要dbSelect来获取ResultSet并返回它。这就是我所拥有的:

public class Utils {
    public static void dbSelect(String query){
        selectQuery = query;
        Thread selectThread = new selectThreadClass();
        selectThread.start();
    }
}
class selectThreadClass extends Thread {
    public void run(){
        perform();
    }

    public ResultSet perform(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lob/?user=root&password=");

            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(Utils.selectQuery);
            return rs;
        }catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e){
            e.printStackTrace();
            return null;
        }
    }
}

任何人都可以帮助我获取它,以便dbSelect从线程中返回ResultSet吗?谢谢!

5 个答案:

答案 0 :(得分:4)

使用Callable

 public interface Callable<V> {
 V call() throws Exception;
}

答案 1 :(得分:2)

而不是Runnable使用callable。

public class SelectCallableClass implements Callable<ResultSet> {

    public ResultSet call() throws Exception {
        return perform();
    }

    public ResultSet perform(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lob/?user=root&password=");

            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(Utils.selectQuery);
            return rs;
        }catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e){
            e.printStackTrace();
            return null;
        }
    }
}

要提交Callable类,请使用ExecuterService

ExecutorService service=Executors.newFixedThreadPool(1);
Future future=service.submit(new SelectCallableClass());
  

上面的代码执行以下操作(来自doc)。提交一个返回值的任务以执行并返回Future&gt;表示任务的待定结果。未来的获取方法   成功完成后将返回任务的结果。

答案 2 :(得分:1)

从我的结束尝试

我修改了代码并使用List来获取解决方案来保存ResultSet中的值,但我只有一个问题 也就是说,我无法将结果作为Callable

中的类型(ResultSet)

当我尝试时,结果集以某种方式显示为空 使用future get()函数

检索值

ResultSet rs =(ResultSet)future.get();

下面是一段没有用的代码,

ExecutorService service=Executors.newFixedThreadPool(1);
Callable<ResultSet> callable = new SelectThreadResultSet();
Future<ResultSet> future = service.submit(callable);
ResultSet rs = (ResultSet)future.get();
// Here I dont get any values
while(rs.next()){
    System.out.println(rs.getString("EMPLOYEE"));
}

请在下面找到适用于我的解决方案,我使用了List 保持价值并将其归还。

class SelectThreadClass:

public class SelectThreadClass implements Callable<List<String>> {

    public List<String> call(){
        ResultSet rs = null;
        List<String> strList = new ArrayList<String>();
        try {
            rs  = perform();
            while(rs.next()){
                strList.add(rs.getString("EMPNAME"));
            }
            System.out.println("Passed");

        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            e.printStackTrace();
        }
        return strList;
    }

    public ResultSet perform() throws InstantiationException, IllegalAccessException, SQLException{
        Connection conn = null;
        try {
            Class.forName("org.sqlite.JDBC");
            try {
                conn = DriverManager.getConnection("jdbc:sqlite:C:\\SqlLite\\EMPLOYEE.db");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Statement s = null;
            try {
                s = conn.createStatement();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            ResultSet rs = null;
            try {
                rs = s.executeQuery(Utils.selectQuery);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return rs;
        }catch (ClassNotFoundException e){
            e.printStackTrace();
            return null;
        }
    }
}

类实用程序:

public class Utils {

    public static String selectQuery = "SELECT EMPNAME FROM EMPLOYEEDETAILS";
    public static void dbSelect(String query) throws InterruptedException, ExecutionException, SQLException{
        ExecutorService service=Executors.newFixedThreadPool(1);
        Callable<List<String>> callable = new SelectThreadClass();

        Future<List<String>> future = service.submit(callable);

        List<String> empList = future.get();
        for(String emp : empList){
            System.out.println(emp);
        }
    }

    public static void main(String args[]) throws InterruptedException, ExecutionException, SQLException{
        dbSelect("SELECT EMPNAME FROM EMPLOYEEDETAILS");
    }

}

答案 3 :(得分:0)

run不会返回结果 在wait中使用al Callable或使用共享变量并轮询/ Utils,直到SelectThreadClass的结果可用。
但我建议使用Callable,因为它完全适合任务

答案 4 :(得分:0)

您可以在Thread类中拥有一个属性,然后获取该属性,

public class Utils {
    public static void dbSelect(String query){
        selectQuery = query;
        Thread selectThread = new selectThreadClass();
        selectThread.start();

        ((SelectThreadClass) selectThread).getResult();
    }
}

class selectThreadClass extends Thread {
    ResultSet rs = null;

    public ResultSet getResult(){
        return rs;
    }

    public void run(){
        rs = perform();
    }

    public ResultSet perform(){
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection("jdbc:mysql://localhost/lob/?user=root&password=");

            Statement s = conn.createStatement();
            return s.executeQuery(Utils.selectQuery);
        } catch (SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException e){
            e.printStackTrace();
            return null;
        }
    }
}

唯一的问题是你最终可能会从你的dbutil中处理连接闭包和其他东西,或者你可以将结果集转换为任何java类,然后返回那个java对象列表而不是结果集