使用内部锁进入块 [英] Entering in block with an Intrinsic Lock

查看:103
本文介绍了使用内部锁进入块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有看到以下代码如何产生看似违反对象锁定义的输出。当然只允许一个线程打印获取锁定消息,但他们都这样做?

I don't see how the following code produces output that appears to contravene the definition of an object lock. Surely only one thread should be allowed to print the "acquired lock" message yet they both do?

class InterruptThreadGroup {
    public static void main(String[] args) {
        Object lock = new Object();
        MyThread mt1 = new MyThread(lock);
        MyThread mt2 = new MyThread(lock);
        mt1.setName("A");
        mt1.start();
        mt2.setName("B");
        mt2.start();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
        }
        // Thread.currentThread().getThreadGroup().interrupt();
    }
}

class MyThread extends Thread {
    private Object lock;

    public MyThread(Object l) {
        this.lock = l;

    }

    public void run() {
        synchronized (lock) {
            System.out.println(getName() + " acquired lock");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                System.out.println(getName() + " interrupted.");
            }
            System.out.println(getName() + " terminating.");
        }
    }
}


推荐答案

这是因为对 lock.wait()的调用释放了锁,允许第二个线程进入同步块。摘自 javadoc

It is because the call to lock.wait() releases the lock, allowing the second thread to enter the synchronized block. Extract from the javadoc


线程释放此监视器的所有权并等待,直到另一个线程通知调用此对象的监视器上的线程唤醒notify方法或notifyAll方法。然后线程等待,直到它可以重新获得监视器的所有权并继续执行。

The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

请注意,您的代码中存在一些问题,例如:

Note that there are a few issues in your code such as:


  • 你不应该在一个循环之外等待

  • 没有任何通知,所以你的等待可以永远持续

  • 让你的任务实现Runnable并将其作为参数传递给Thread的构造函数而不是直接扩展Thread是一种更好的做法。

这篇关于使用内部锁进入块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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