Java synchronized block not working

后端 未结 2 1300
盖世英雄少女心
盖世英雄少女心 2020-12-21 15:26

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

I only want one account to be processed at a time by ea

相关标签:
2条回答
  • 2020-12-21 16:05

    Each thread is executing with a different instance of TC.

    new Thread(new TC())
    

    So when you do:

    synchronized (this)
    

    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)
    
    0 讨论(0)
  • 2020-12-21 16:21

    The whole point of synchronization is, when there is a shared resource and multiple threads accessing it.

    In your case,same TC instance can be passed into new Thread.then 3 threads start working on it.

    Now the db operation needs to be protected, since you need to get account info and also update timestamp.so synchronize on a lock object specifically or this.

    private Object lock = new Object();

    0 讨论(0)
提交回复
热议问题