gpt4 book ai didi

java - 多线程——共享数据

转载 作者:行者123 更新时间:2023-12-02 00:35:08 25 4
gpt4 key购买 nike

我在面试中被问到以下问题。

There is an object which is being shared by multiple threads. The object has the following function. How can you make sure that different threads can execute the functions simultaneously for different values of parameter x? If two threads are executing with same value of x, one of them should be blocked.

public void func(String x){
-----
}

“synchronized”关键字在这种情况下不起作用,因为它将确保一次只能执行一个线程。请告诉我这个问题的解决方案是什么

最佳答案

第一个想到的就是这样

public void func(String x){
synchronized (x.intern()) {
// Body here
}
}

这将按照描述进行操作;当然,这感觉像是一个令人讨厌的黑客行为,因为同步的对象是可公开访问的,并且其他代码可能会干扰锁定。

关于java - 多线程——共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14995352/

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