带有MYSQL的Java线程令人困惑 [英] Java Threading with MYSQL puzzled
问题描述
我对MySQL和Java线程的行为感到非常困惑.我将其声明为已同步,并且得到的结果发生了冲突.这意味着一个以上的线程正在同时访问同一功能.此代码段在runnable类中. MachineID是在for循环中调用的线程ID. (这是一个从1到100的数字).
I am very puzzled by the behavior of MySQL and java threading. I declare this as synchronized and the results I get are clashing. That means that more than one thread is accessing the same function at the same time. This code segment is in the runnable class. MachineID is the thread id in the order with which it was invoked in the for loop. (It is jsut a number from 1 to 100).
我认为该表不是
这是我得到的输出
144 18
144 17
144 11
144 13
144 10
144 9
public synchronized int getRow() throws SQLException{
String query="SELECT * FROM Searches WHERE checked='0'";
ResultSet results = this.database.executeQuery(query);
int id=0;
if(results.next()){
id=results.getInt(1);
System.out.println(id+" "+this.machineID);
query = "UPDATE Searches SET checked='1' WHERE ID_num='"+id+"'";
System.out.println(this.database.executeUpdate(query));
}
return id;
}
public void run() {
int id=getRow();
if (id!=0) {
}
}
这是我调用线程的地方
for (int i = 0; i < verifier.length; i++) {
verifier[i]=new Thread(new Verifier(main.database,i+1));
verifier[i].start();
}
推荐答案
假定getRow()
方法属于Verifier
类,则不会发生阻塞.在方法上声明synchronized
时,它等效于在实例本身上进行同步.但是,您正在为每个Thread
生成一个新的Verifier
实例.每一个都在自己同步,所以没有一个会阻塞其他任何人.
Assuming the getRow()
method belongs to the Verifier
class, then there is no blocking going on. When you declare synchronized
on a method, it is equivalent to synchronizing on the instance itself. However, you are spawning a new Verifier
instance for each Thread
. Each of those is synchronizing on themselves so none block any of the others.
考虑与Verifier
的每个实例共享一个Lock
对象,或在共享的对象上进行同步.
Consider sharing a Lock
object with each instance of Verifier
or synchronizing on a shared object.
Object lock = new Object();
for (int i = 0; i < verifier.length; i++) {
verifier[i]=new Thread(new Verifier(main.database,i+1, lock));
verifier[i].start();
}
...
public int getRow() throws SQLException{
synchronized(lock) {
...
}
}
这篇关于带有MYSQL的Java线程令人困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!