简体   繁体   中英

Java Multithreading

我有一个要求,我必须访问数据库,并将这些值放在一个列表中,然后使用多个线程打印这些值。目前我使用2个线程,我的输出是这样的,每个线程建立单独的数据库连接,并迭代整个列表,因此在输出我得到每个值两次.pl帮助解决这个问题

Why not use connection pooling instead? http://sourceforge.net/projects/c3p0/

Age old divide and conquer technique. Logically split your database into 2 halves (let us say you got to read 100 values from DB then let each thread read 50 values). Merge the data back to a single List and then print off that single list.

//this s my code

class Conn
{ Connection getDBConnection(String serverName,String url,String userid,String password) {
    Connection conObj = null;
    try {Class.forName("oracle.jdbc.OracleDriver");
        conObj = DriverManager.getConnectionurl,userId,password);
        return conObj;}
            catch(Exception e){
            }}}
        class listObj extends Conn
{ List lst;
Connection con;
String query;
public  List resultList() {
    try{//connection code
    query = "select * from test";
      ResultSet rs = st.executeQuery(query);
     lst=new ArrayList();
        while(rs.next())
            {lst.add(rs.getInt(1);}return lst;
     } catch(Exception e)
{ }
     }}
 class Thread1 extends listObj implements Runnable
{ public void run() 
     {List ls=null;
        try {ls=(ArrayList)resultList();
        } catch (Exception e) {
            e.printStackTrace();
        }
          ListIterator it= ls.listIterator();
         while (it.hasNext()){
            System.out.println(it.next());
         } }}    
   class TestMain extends listObj {
    p.s.v.m(String a[]) throws Exception {
        Thread t1=new Thread(new Thread1());
        Thread t2=new Thread(new Thread1());
        t1.start();t2.start();}}

select for update in combination with fetch first n rows is one option.

so if the first thread read n rows, the same will be ignored by the consecutive threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM