gpt4 book ai didi

java - java中的synchronized方法如何保证对对象的不干扰

转载 作者:行者123 更新时间:2023-12-01 17:55:33 26 4
gpt4 key购买 nike

我想确保(我理解正确)并知道java中的同步方法如何保证对对象的不干扰。

例如我有这个代码:

private void update_curr_mat(int stock_ind, double price, double time)
{
synchronized(current_mat_data)
{
current_mat_data[stock_ind][HIGH_PRICE_IND] = price;
current_mat_data[stock_ind][LOW_PRICE_IND] = price;
current_mat_data[stock_ind][CLOSE_IND] = price;
current_mat_data[stock_ind][HIGHEST_IND] = price;
current_mat_data[stock_ind][LOWEST_IND] = price;

current_mat_data[stock_ind][CURR_TIME_IND] = time;
}
}

在此示例中,很明显,current_mat_data 是同步的,并且当调用该方法时,另一个线程无法写入 current_mat_data 对象。

在此示例中:

private synchronized void update_curr_mat(int stock_ind, double price, double time)
{
current_mat_data[stock_ind][HIGH_PRICE_IND] = price;
current_mat_data[stock_ind][LOW_PRICE_IND] = price;
current_mat_data[stock_ind][CLOSE_IND] = price;
current_mat_data[stock_ind][HIGHEST_IND] = price;
current_mat_data[stock_ind][LOWEST_IND] = price;

current_mat_data[stock_ind][CURR_TIME_IND] = time;
}

同步是在方法定义中完成的。我知道它保证两个线程不能同时调用这个方法。

所以我的问题是,在调用第二个 exmaple 中的函数时,保证其他线程无法访问对象 current_mat_data 吗?如果这是真的,你能解释一下它是如何工作的吗?如果我写的内容不正确或不清楚,请告诉我。

最佳答案

两个示例中,没有绝对保证(仅给出您所显示的内容)没有任何东西可以编辑对象。也就是这个语句

In this example it is obvious, that current_mat_data is synchronized, and when the method invoked, another thread can't write to current_mat_data object.

不正确。

唯一的保证是没有两个线程可以同时持有同一个锁;并且线程必须持有适当的锁才能执行同步块(synchronized block)或方法(因此,如果另一个线程持有该锁,则该线程必须等待直到该锁变得可用,然后才能获取该锁并进入同步块(synchronized block)或方法)。

您必须使用封装和良好的编程来构建任何额外的保证。

令人困惑的是,每个对象都可以用作锁,但您不一定必须持有对象的锁才能编辑该对象。也就是说,Java 并不要求你拥有锁来编辑对象。为了强制执行这样的规则,您需要可以编辑对象的所有方法,以将其包含在使用该对象作为锁的同步块(synchronized block)或方法中。

两个示例之间的区别只是哪个对象用作锁。第一个示例使用 current_mat_data 引用的对象;第二个使用 this 引用的对象(调用 update_cur_mat 方法的对象实例)。 (静态方法将使用类对象。)

关于java - java中的synchronized方法如何保证对对象的不干扰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45223197/

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