1. Java 并发volatile 问题代码
class NumberDemo {
//private AtomicInteger count = new AtomicInteger(0);
private volatile int count = 0;
public void add() {
this.count++;
}
public int getCount() {
return this.count;
}
}
public class ThreadDemo {
public static void main(String[] args) {
NumberDemo d = new NumberDemo();
//CountDownLatch latch = new CountDownLatch(10);
for (int i = 1; i <= 10; i++) {
new Thread(()-> {
for (int j = 1; j <= 100; j++) {
d.add();
}
}).start();
}
if (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println("count is :" + d.getCount());
}
1. 问题这个count 虽然添加了volatile ,但是count++ 不是原子的.
2.主线程在启动所有子线程后,通过检查 Thread.activeCount() > 1
并调用 Thread.yield()
尝试等待子线程完成。这种方式不可靠,因为:
Thread.activeCount()
返回的线程数包含主线程自身,判断逻辑不准确。Thread.yield()
仅让出当前线程的 CPU 时间片,但无法确保所有子线程执行完毕。
主线程可能提前输出结果,而子线程尚未完成所有累加操作,导致输出值远小于 1000, 其实个人答错这道题是因为忘记volatile 只能保证可见性,无法保证原子性,还有就是这个yield我从来没有用过。
class NumberDemo {
//private AtomicInteger count = new AtomicInteger(0);
private volatile int count = 0;
public synchronized void add() {
this.count++;
}
public int getCount() {
return this.count;
}
}
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
NumberDemo d = new NumberDemo();
Thread [] threads = new Thread[10];
//CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(()-> {
for (int j = 1; j <= 100; j++) {
d.add();
}
});
threads[i].start();
}
for(Thread t: threads){
t.join();
}
System.out.println("count is :" + d.getCount());
}
}
2. 现成的run 问题
Thread t = new Thread(new Runnable() {
@Override
p