使用不同的线程访问数据库 - java

时间:2016-02-04 02:45:56

标签: java multithreading jdbc

我使用两个不同的线程并使用主线程运行reader()方法和reader2()。

在检查了两个案例的时间后,我意识到没有显着差异。

我的疑惑:通过JDBC数据访问oracle的基础知识,一次只能进行查询?

谢谢。

public class ReadingTime {

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

    //reader("pessoas");
    //reader("pessoas_dw");

    Thread t1 = new Thread(new Runnable() {
        @Override
        public void run() {
            reader("pessoas");
        }
    });

    Thread t2 = new Thread(new Runnable() {
        @Override
        public void run() {
            reader2("PESSOAS_DW");
        }
    });

    t1.start();
    t2.start();

    t1.join();
    t2.join();

}

public static void reader(String s){
    long tempoInicial = System.currentTimeMillis();
    MyConnection conn = new MyConnection("oracle", "localhost", "1521", "orcl", "username1", "password1");
    conn.openConnection();
    Statement st = conn.createStatement();
    ResultSet tabela1 = conn.executeQuery(st, "select * from "+s);
    int i = 1;
    try {
        while(tabela1.next()){
            i++;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Thread 1");
    System.out.println(i);
    long tempoFinal = System.currentTimeMillis();
    System.out.println( tempoFinal - tempoInicial );
    System.out.println("____________________________");

}

public static void reader2(String s){
    long tempoInicial = System.currentTimeMillis();
    MyConnection conn = new MyConnection("oracle", "localhost", "1521", "orcl", "username2", "password2");
    conn.openConnection();
    Statement st = conn.createStatement();
    ResultSet tabela1 = conn.executeQuery(st, "select * from "+s);
    int i = 1;
    try {
        while(tabela1.next()){
            i++;
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Thread 2");
    System.out.println(i);
    long tempoFinal = System.currentTimeMillis();
    System.out.println( tempoFinal - tempoInicial );
    System.out.println("__________________________");

}

1 个答案:

答案 0 :(得分:0)

我要在这里猜一猜。 您不会关闭结果集,语句和连接(特别是不关闭连接)。

我的猜测是MyConnection(我们看不到)可能在同一(主)线程上重用之前的连接。

因此,假设连接建立时间远远大于结果集迭代,那么它就有意义了。

尝试关闭rs,st和conn以查看它是否有所作为。