共计 639 个字符,预计需要花费 2 分钟才能阅读完成。
示例
public class AtomicDemo {
static int num1 = 0;
static AtomicInteger num2 = new AtomicInteger(0);
static class Thread1 extends Thread {
@Override
public void run() {
try {sleep(100);
} catch (InterruptedException e) {e.printStackTrace();
}
num1++;
}
}
static class Thread2 extends Thread {
@Override
public void run() {
try {sleep(100);
} catch (InterruptedException e) {e.printStackTrace();
}
num2.incrementAndGet();}
}
public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 1000; i++) {new Thread1().start();
new Thread2().start();
}
Thread.sleep(2000);
System.out.println("num1=" + num1);
System.out.println("num2=" + num2.get());
}
}
运行结果如下:
在多线程无锁的情况下,num1 总是小于等于 1000,而 num2 因为原子性的方法总是等于 1000。
正文完
发表至: java
2019-07-14