gpt4 book ai didi

java - java中的不正确同步

转载 作者:行者123 更新时间:2023-11-29 04:30:58 25 4
gpt4 key购买 nike

所以,我正在尝试了解 Java 线程和同步。下面这段代码没有正确同步,谁能解释一下原因?

package threadPractice;

public class T2 extends Thread {
public static int count=0;
public T2( ) { }
private synchronized void update( ) {
int v = count;
try {
sleep(10);
} catch (Exception e) { }
v++;
count = v;
}
public void run( ) {
for (int i = 0; i < 1000; i++) {
update( );
}
}
}
package threadPractice;

public class Main {
public static void main(String args[]) throws Exception {
T2 t1_1 = new T2( );
T2 t1_2 = new T2( );
t1_1.start( ); t1_2.start( );
t1_1.join( ); t1_2.join( );
System.out.println("T2.start, "+T2.count);

}
}

我的预期输出是 2000。我的实际输出是在 0 到 2000 之间。

最佳答案

嗯,因为你让两个不同的对象同步。如果您想要一把锁来保护一个字段 (count),您需要使用一把锁。为每个线程提供自己的锁意味着任何线程都不知道其他线程何时实际使用锁。

首先,如果您的领域是公开的,则没有任何内容受到保护。将其设为私有(private)。

第二种在这种情况下使用静态方法来保护静态字段。

public class T2 extends Thread {
private static int count=0;

private static synchronized void update( ) {
int v = count;
try {
sleep(10);
} catch (Exception e) { }
v++;
count = v;
}

@Override
public void run( ) {
for (int i = 0; i < 1000; i++) {
update( );
}
}
}

此外,synchronizedwait/notify 是具有许多尖角的低级原语(如您所见)。更好的选择是使用 API。

public class T2 extends Thread {
private static final AtomicInteger count = new AtomicInteger();

@Override
public void run( ) {
for (int i = 0; i < 1000; i++) {
count.incrementAndGet();
}
}
}

关于java - java中的不正确同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788700/

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