gpt4 book ai didi

java - 为什么这个线程不安全

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

示例一:

public class Test { 
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
Runnable t1 = new MyRunnable("A", 2000);
Runnable t2 = new MyRunnable("B", 3600);
Runnable t3 = new MyRunnable("C", 2700);
Runnable t4 = new MyRunnable("D", 600);
Runnable t5 = new MyRunnable("E", 1300);
Runnable t6 = new MyRunnable("F", 800);

pool.execute(t1);
pool.execute(t2);
pool.execute(t3);
pool.execute(t4);
pool.execute(t5);
pool.execute(t6);

pool.shutdown();
}
}

class MyRunnable implements Runnable {
private static AtomicLong aLong = new AtomicLong(10000);
private String name;
private int x;

MyRunnable(String name, int x) {
this.name = name;
this.x = x;
}

public void run() {
System.out.println(name + " excute" + x + ",money:" + aLong.addAndGet(x));
}
}

此线程在此示例中不安全。

示例二

public class CountingFactorizer implements Servlet { 
private final AtomicLong count = new AtomicLong(0);

public void service(ServletRequest req, ServletResponse resp) {
count.incrementAndGet();
}
}

为什么这个线程是安全的?有人可以告诉我吗?

我正在研究java中的线程,但无法理解两个示例。它们有什么不同吗?

最佳答案

据我所知,两者都是线程安全的。在这两个示例中,静态类级别成员都是 AtomicLong,根据定义它是线程安全的。第一个示例中的所有其他成员都是实例级成员,并且在不同的线程中执行,因此根本不存在冲突。

关于java - 为什么这个线程不安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33117708/

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