Threading in Java: How to lock an object?

前端 未结 7 699
长发绾君心
长发绾君心 2020-12-29 03:33

The following Function is executing in its own thread:

private void doSendData()
{
    try {

           //writeToFile(); // just a temporary location of a c         


        
相关标签:
7条回答
  • 2020-12-29 04:31

    Below code should work.

         private final ReentrantLock lock = new ReentrantLock();
    
         lock.lock();  // block until condition holds
         try {
            serverAddr.wait(60000);
         } finally {
           lock.unlock()
         }
       }
    

    Refer to this documentation page for more details.

    public void lock()
    

    Acquires the lock.

    Acquires the lock if it is not held by another thread and returns immediately, setting the lock hold count to one.

    If the current thread already holds the lock then the hold count is incremented by one and the method returns immediately.

    If the lock is held by another thread then the current thread becomes disabled for thread scheduling purposes and lies dormant until the lock has been acquired, at which time the lock hold count is set to one

    Refer to this SE question to know the advantages of lock over synchronization:

    Synchronization vs Lock

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