有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java线程同步和单例问题

首先,我需要清除一些基本的东西,假设我有一个同步块或同步方法,一个线程已经进入同步部分,5个新线程尝试访问同步部分,它们会停止运行,直到第一个线程离开同步部分吗?如果他们这样做了,他们会按优先顺序排队吗

第二个问题是关于监视器,假设我有以下代码:
synchronized(someObject){ //do some stuff someObject.wait(); } 假设一个线程在另一个线程在监视器上等待时运行此代码,然后第一个线程调用wait,那么第二个线程将进入代码块(即wait释放someObject的监视器),这是否正确

最后一个问题是关于单例实现,为了保证线程安全,同步单例类中的实例化行以确保它不会被多次调用是否足够?如果是这样,这是最佳实践吗


共 (1) 个答案

  1. # 1 楼答案

    First off I need to clear something basic, assume I have a synchronized block or a synchronized method and one thread already entered the synchronized part and 5 new threads try to access the synchronized part, will they stop running until the first thread leaves the synchronized part? and if they do, will they wait in a prioritized queue?

    如果一个线程在监视器上有锁,那么其他线程无法在同一对象上获得相同的锁。因此,他们将被封锁。一旦当前线程放弃了锁,另一个线程就可以获得锁。就优先级而言,即使一个线程的优先级高于另一个线程,也不能保证优先级较高的线程会在优先级较低的线程之前运行

    ReentrantLock类构造函数提供了创建公平锁或非公平锁的可能性。在公平场景中,线程按照请求的顺序获取对象上的锁。在不公平的情况下,允许请求的转发,其中一个请求可能会在请求队列的更高位置上转发

    Second question is regarding monitors, assume I have a the following code:

    synchronized(someObject){
            //do some stuff
            someObject.wait();
    }
    

    Is it correct to assume that if a thread runs this code while another thread is waiting on the monitor and then the first thread calls wait, the second thread will enter the code block (I.E. the wait releases someObject's monitor) ?

    当当前线程调用wait时,当前线程将释放它对对象的所有锁。一旦释放该锁,其他线程可能会尝试在同一对象上获取相同的锁

    And last question is regarding a Singleton implementation, in order to make it thread safe is it enough to synchronize the instantiation line inside the singleton class to make sure it never gets called more than once ? and if so, is this the best practice ?

    请参阅this关于线程安全的单例类的帖子