gpt4 book ai didi

java - 并发同步问题

转载 作者:行者123 更新时间:2023-12-01 12:45:32 25 4
gpt4 key购买 nike

public class Demo {
public Demo() {
}

public static void main(String[] args) {
Concurrency c = new Concurrency();
Thread t1 = new Thread(c);
t1.setName("t1");
Thread t2 = new Thread(c);
t2.setName("t2");
Thread t3 = new Thread(c);
t3.setName("t3");
Thread t4 = new Thread(c);
t4.setName("t4");

t1.start();
t2.start();
t3.start();
t4.start();
}
}


class Concurrency implements Runnable {
private String value= new String("I");
static Integer s =2;

@Override
public void run() {
function();
}

public void function() {
synchronized(s){

s = s * 5;
System.out.println("Current thread is " + Thread.currentThread() + s);
// s.notify();
}
}

我编写了示例程序来测试同步。我得到以下输出:

Current thread is Thread[t2,5,main]50
Current thread is Thread[t3,5,main]1250
Current thread is Thread[t4,5,main]1250
Current thread is Thread[t1,5,main]50

这意味着当多个线程运行时,同步也无法同步,并且当如上所述调用 s.notify() 时,我还会收到 IlleagalMonitorStateException

请让我知道它到底在做什么以及为什么同步失败。也欢迎我解决这个问题。

//调用 s.notify() 后,我收到以下错误。

 Exception in thread "t1" Exception in thread "t2" Exception in thread "t3"   
java.lang.IllegalMonitorStateException
Current thread is Thread[t1,5,main]50
Current thread is Thread[t2,5,main]50
Current thread is Thread[t3,5,main]250
Current thread is Thread[t4,5,main]1250
at java.lang.Object.notify(Native Method)
at Concurrency.function(Demo.java:42)
at Concurrency.run(Demo.java:32)
at java.lang.Thread.run(Unknown Source)
Exception in thread "t4" java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Concurrency.function(Demo.java:42)
at Concurrency.run(Demo.java:32)
at java.lang.Thread.run(Unknown Source)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Concurrency.function(Demo.java:42)
at Concurrency.run(Demo.java:32)
at java.lang.Thread.run(Unknown Source)
java.lang.IllegalMonitorStateException
at java.lang.Object.notify(Native Method)
at Concurrency.function(Demo.java:42)
at Concurrency.run(Demo.java:32)
at java.lang.Thread.run(Unknown Source)

最佳答案

当你这样做

s = s * 5;

您正在将一个对象分配给s,因此同步实际上适用于不同对象,因此本质上是被破坏的。幕后真正发生的事情类似于

s = new Integer(s.intValue() * 5);

您需要的是一个并发安全的可变整数容器。幸运的是有“AtomicInteger”。

static final AtomicInteger s = new AtomicInteger(2);

...

s.getAndSet(s.get()*5);

关于java - 并发同步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24737055/

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