java - multithreading and JDBC -
i use java , oracle , want use 2 threads read records result set : first thread retrieve records , second read these records.but code obtained first record idea please?
public class javaapplication13 { public static volatile boolean finished =false; public static void main(string[] args) throws ioexception, interruptedexception { final pipedwriter writer=new pipedwriter(); final pipedreader reader = new pipedreader(); reader.connect(writer); //thread2: afficher final thread thread2=new thread("lire") { public void run(){ try{ while(!finished) { int l=reader.read(); system.out.println(l); } }catch (exception e) { e.printstacktrace();} } }; //thread1:récupére de la base final thread thread1=new thread("db"){ public void run(){ try{ class.forname("com.mysql.jdbc.driver"); connection conn=drivermanager.getconnection("jdbc:mysql://localhost:3306/stage","root", ""); statement s=conn.createstatement(); string sql = "select idetudiant etudiant"; resultset rs=s.executequery(sql); while(rs.next()){ int k= rs.getint("idetudiant"); writer.write(k); } finished=true; } catch (exception e) { e.printstacktrace(); } } }; thread2.start(); thread1.start(); thread2.join(); }
}
there buffer between 2 threads; feature of pipes.
so happens thread1
puts lot of data pipe's buffer , sets finished
true
.
when enough data in pipe, thread2
start. @ time, finished
true
, thread read first item , quit.
solution: rid of variable. flush , close pipe writer
in thread1
when it's done:
final thread thread1=new thread("db"){ public void run(){ try{ ... } catch (exception e) { e.printstacktrace(); } writer.close(); // send eof other thread } };
in thread2
, read pipe reader
until read()
returns eof (-1):
final thread thread2=new thread("lire") { public void run(){ try{ while(true) { int l=reader.read(); if(-1 == l) break; // eof system.out.println(l); } }catch (exception e) { e.printstacktrace();} } };
Comments
Post a Comment