我有三个主题:
thread1:
run() {
while(true) {
List<Document> documents = getDocumentsFromExternalService()
//executes "insert into .." sql query:
insertDocumentsToDatabase(documents)
Thread.sleep(5000);
}
}
thread2:
run() {
while(true) {
//connects to database and execute "Select * from DOCS WHERE DOCS.STATE='STATE_1" query:
List<Documents> docs = getDocumentsFromDatabaseWithState("STATE_1")
docsChanged = doSomethingWith(docs)
//perform "update" SQL instruction:
updateDocumentsInDatabase(docsChanged)
Thread.sleep(5000);
}
}
thread3:
run() {
while(true) {
//connects to database and execute "Select * from DOCS WHERE DOCS.STATE='STATE_2'" query:
List<Documents> docs = getDocumentsFromDatabaseWithState("STATE_2")
docsChanged = doSomethingOtherWith(docs)
//perform "update" SQL instruction:
updateDocumentsInDatabase(docsChanged)
Thread.sleep(5000);
}
}
所有连接都是标准的JDBC连接,并且每个线程都是独立的。问题是如何实现线程安全?这意味着 - 如何确保在执行thread2线程3的读取函数之前没有写入数据库?
答案 0 :(得分:0)
使用数据库中的事务进行写入。
connection.setAutoCommit(false);
// do you're thing
connection.commit();
connection.setAutoCommit(true);
请参阅:http://docs.oracle.com/javase/tutorial/jdbc/basics/transactions.html