- class Test {
- static int i = 0, j = 0;
- static synchronized void one() { i++; j++; }
- static synchronized void two() {
- System.out.println("i=" + i + " j=" + j);
- }
- }
- synchronized,每次都要判断锁
和
- class Test {
- static volatile int i = 0, j = 0;
- static void one() { i++; j++; }
- static void two() {
- System.out.println("i=" + i + " j=" + j);
- }
- }
- volatile,每次强迫线程重读值和重写值
哪种效率更高?
|
|