Java synchronized块无法正常工作 [英] Java synchronized block not working

查看:125
本文介绍了Java synchronized块无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多线程java应用程序,它从Postgresql数据库中检索用户名以进行处理。

I have a multi threaded java application that retrieves usernames from a Postgresql database for processing.

我只希望每个线程一次处理一个帐户,所以我的表中有一个列,其中包含上次访问的时间戳,只有已被访问超过30秒将被提取。 SQL查询在下面工作,我只是发布它是明确的。

I only want one account to be processed at a time by each thread so I have a column in my table which has the time stamp of last accessed and only accounts which have been accessed more than 30 seconds will be fetched. The SQL Query works below, I'm only posting it to be clear.

select * from account where (EXTRACT(EPOCH FROM (now() - last_accessed)) > 30 OR last_accessed is null) AND enabled = true order by random() limit 1

我有一个同步的块,所以只有一个线程可以访问帐户检索过程,因为更新时间戳会占用数据库的时间。

I have a synchronized block so only one thread can access the account retrieval process as the updating the time stamp takes a bid of time on the database.

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();
        }
    }
}

但我仍然收到相同的我运行程序时的帐户。我做错了什么?

But I still receive the same account when I run the program. What I am doing incorrectly?

推荐答案

每个线程都使用 TC

new Thread(new TC())

所以当你这样做时:

synchronized (this)

每个线程正在同一个不同的对象上进行同步(不同的 TC ),所以他们根本没有相互竞争。从本质上讲,同步块变得毫无意义。

Each thread is synchronizing on a different object (different TC), so they are not competing with each other at all. Essentially, the synchronized block becomes pointless.

我不确定这是一个多么好的想法,但你要做的就是这样完成:

I'm not sure how good of an idea this is, but what you are trying to do would be accomplished like this:

synchronized (TC.class)

或者,或许更清洁一点,通过在类中声明一个静态成员并同步它:

or, perhaps a bit cleaner, by declaring a static member in the class and synchronizing on that:

private static final Object _lock = new Object();

....

synchronized(_lock)

这篇关于Java synchronized块无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆