Jer*_*yJi 1 java multithreading compare-and-swap
众所周知,i ++在java中不是原子的,所以我尝试编写一个程序来证明这一点.
我的想法是新增几个线程并在每个线程内部增加计数(这是Main类中的静态字段).
如果
threadNum * iteration > count,
Run Code Online (Sandbox Code Playgroud)
那么我们可以证明i ++不是原子的,但实际上我总是让它们相等.
这是我的代码:
import java.util.ArrayList;
import java.util.List;
public class ConcurrentTest{
private static int count = 0;
public static void main(String[] args) throws Exception{
List<Thread> threads = new ArrayList<>();
for(int i = 0; i<12; ++i){
threads.add(new Thread(() -> {
for(int j=0; j<1000000; ++j) {
count++;
}
}));
}
for(Thread t: threads){
t.start();
t.join();
}
System.out.println(count);
}
}
Run Code Online (Sandbox Code Playgroud)
结果是12000000.
并且无论我如何在上述程序中改变i和j, i*j === count.
我不知道这是否有用:这个程序已在JRE 6,7和8上测试过.我还没有在Java 5或更早版本中测试它.
该join方法使当前正在执行的线程等待完成调用它的线程.在你的代码中,你启动一个线程,然后等待它完成,然后启动另一个.
更改
for(Thread t: threads){
t.start();
t.join();
}
Run Code Online (Sandbox Code Playgroud)
至
for(Thread t: threads){
t.start();
}
for(Thread t: threads){
t.join();
}
Run Code Online (Sandbox Code Playgroud)
这将启动所有线程运行,然后等待它们全部完成.
| 归档时间: |
|
| 查看次数: |
81 次 |
| 最近记录: |