我想多線程的結果集。我想確保每當我在其中一個線程中調用next()
時,所有其他線程都被鎖定。這很重要,因爲如果許多線程同時調用next()
方法,這將導致跳過行。這是我做的同步鎖定結果集對象嗎?
public class MainClass {
private static ResultSet rs;
public static void main (String [] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
runWhile();
}});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
runWhile();
}});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.exit(0);
}
private static void runWhile() {
String username = null;
while ((username = getUsername()) != null) {
// Use username to complete my logic
}
}
/**
* This method locks ResultSet rs until the String username is retrieved.
* This prevents skipping the rows
* @return
* @throws SQLException
*/
private synchronized static String getUsername() throws SQLException {
if(rs.next()) {
return rs.getString(1).trim();
}
else
return null;
}
}
這是使用的正確方法。它鎖定ResutSet
並確保其他線程不會干擾?
這是一個很好的方法嗎?
我將有一個線程讀取ResultSet將任務添加到ExecutorService。 –
謝謝。我有一種感覺,我的方法是錯誤的。雖然它有效,但它感覺不對 –
它會以這種方式工作。但訂單不能保證。 – gba