gpt4 book ai didi

java - 线程同步和单例问题

转载 作者:行者123 更新时间:2023-11-30 03:26:49 28 4
gpt4 key购买 nike

首先我需要清除一些基本的东西,假设我有一个同步块(synchronized block)或同步方法,并且一个线程已经进入同步部分并且5个新线程尝试访问同步部分,它们会停止运行直到第一个线程离开同步部分?如果他们这样做,他们会在优先队列中等待吗?

第二个问题是关于监视器,假设我有以下代码:
同步(someObject){
//做一些事情
someObject.wait();
}
假设如果一个线程运行此代码,而另一个线程正在监视器上等待,然后第一个线程调用 wait,第二个线程将进入代码块(即等待释放 someObject'显示器)?

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

最佳答案

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关于线程安全单例类的帖子。

关于java - 线程同步和单例问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30002563/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com