我有一个多线程java应用程序,它从Postgresql数据库检索用户名以进行处理。Java同步块不能正常工作
我只希望每个线程一次处理一个帐户,因此我的表中有一列有上次访问的时间戳,只有超过30秒的访问权限的帐户才会被提取。 SQL查询的作品如下,我只是发布它是明确的。
我有一个synchronized块,从而将更新时间戳花费的时间是数据库的出价只有一个线程可以访问该帐户检索过程。
public class TC extends Common implements Runnable
{
RegularExpr reg = new RegularExpr();
Database db = new Database();
public void run()
{
while (true)
{
try
{
ArrayList<Object> accountInfo = null;
synchronized (this)
{
accountInfo = db.getAccount();
db.updateAccountAccessTime((String) accountInfo.get(0));
Thread.sleep(3000);
}
System.out.println((String) accountInfo.get(0));
Thread.sleep(9999999);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
我的主类
public class Main
{
public static void main(String[] args)
{
for (int i = 0; i < 3; i++)
{
System.out.println("Inside loop to create threads!");
Thread newThread = new Thread(new TC());
newThread.start();
}
}
}
但我仍然收到相同的帐户,当我运行程序。我做错了什么?
我该如何实现我所需要的? – Arya
您将不得不在TC类上使用静态最终对象,并使用它来同步而不是使用它。 – Codebender