1

同期メソッドを使用して、スレッドで Java プログラムを作成しようとしています。しかし、別のスレッドがJavaで同期メソッドを呼び出したときに、スレッドがすでに実行されていることをどのように表示できるかを理解できません。誰でも簡単な例で説明できますか

4

2 に答える 2

3

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");
    }
}
于 2012-12-10T08:01:20.373 に答える
0

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.

于 2012-12-10T08:36:00.270 に答える