简体   繁体   中英

locks on java synchronized methods

I am trying to write a java program with threads using synchronized methods. But iam not able to understand how can i display that already a thread is running when another thread invokes synchronized method in java. Can any one explain with simple example

Here is a contrived example which shows the interleaving and blocking process. On my machine it prints:

Thread[Thread-0,5,main] is going to call the synchronized method
Thread[Thread-1,5,main] is going to call the synchronized method
Thread[Thread-0,5,main] is in the synchronized method
Thread[Thread-0,5,main] is exiting the method
Thread[Thread-1,5,main] is in the synchronized method
Thread[Thread-1,5,main] is exiting the method

You can see that only one thread enters the synchronized block while the other waits.

public class Test1 {

    public static void main(String[] args) throws Exception {
        final Test1 test = new Test1();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread() + " is going to call the synchronized method");
                test.method();
            }
        };
        new Thread(r).start();
        new Thread(r).start();
    }

    public synchronized void method() {
        System.out.println(Thread.currentThread() + " is in the synchronized method");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
        }
        System.out.println(Thread.currentThread() + " is exiting the method");
    }
}

If I understand you correctly you want to print a message when a thread tries to invoke a synchronized method while another thread is already executing it. You cannot do this with synchronized methods or blocks but you can do it using java.util.concurrent.locks.Lock interface instead. The method you need is tryLock(). You can do something like this:

public class Test1 {
    private Lock lock = new ReentrantLock();

    // ...

    public void method() {
        if (lock.tryLock()) {
            try {
                // you successfully acquired the lock, do you logic here
            } finally {
                lock.unlock();
            }                
        } else {
            // lock is hold by another thread
            System.out.println("cannot acquire a lock");
        }
    }
}

You can easily evolve this example to print which thread exactly holds the lock if you wish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM