I have a requirement where in I have to access the database and place those values in a list and then print those values using multiple threads.currently i use 2 threads and my output is such that each thread establishes separate connection to database and iterates the entire list and hence in out put i get every value twice.pl help in solvi开发者_高级运维ng this
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.
精彩评论