【发布时间】:2016-05-31 17:38:42
【问题描述】:
我正在尝试对结果集进行多线程处理。我想确保每当我在多个线程之一中调用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;
}
}
这是使用synchronized 的正确方式吗?它是否锁定ResutSet 并确保其他线程不会干扰?
这是一个好方法吗?
【问题讨论】:
-
我会让一个线程读取 ResultSet 并将任务添加到 ExecutorService。
-
谢谢。我有一种感觉,我的方法是错误的。虽然有效,但感觉不对
-
它将以这种方式工作。但不能保证顺序。
-
我不想将您的注意力从 Nathan Hughes 的回答中移开,但您应该也知道将
synchronized添加到您的getUsername()方法中不阻止其他线程使用rs。它所做的只是确保一次只允许一个线程进入getUsername()。
标签: java multithreading jdbc resultset