java - 线程同步为什么不一样
问题描述
package com.dome;
public class Thread01 {
private volatile static int a =10;Thread td1 = new Thread(){public void run(){for(int i=0;i<3;i++){ a = a+1;System.out.println(i+'td1:='+a);} } };Thread td2 = new Thread(){ public void run(){for(int i=0;i<3;i++){ a -=1; System.out.println(i+'td2:='+a);} } };public static void main(String[] args) { Thread01 th = new Thread01(); th.td1.start();th.td2.start(); }
}
0td1:=90td2:=91td1:=101td2:=92td1:=102td2:=9
问题解答
回答1:a = a + 1, a = a - 1 这样的语句,事实上涉及了 读取-修改-写入 三个操作:
读取变量到栈中某个位置
对栈中该位置的值进行加 (减)1
将自增后的值写回到变量对应的存储位置
因此虽然变量 a 使用 volatile 修饰,但并不能使涉及上面三个操作的 a = a + 1,a = a - 1具有原子性。为了保证同步性,需要使用 synchronized:
public class Thread01 { private volatile static int a = 10; Thread td1 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a = a + 1; System.out.println(i + 'td1:=' + a);} }} }; Thread td2 = new Thread() {public void run() { for (int i = 0; i < 3; i++) {synchronized (Thread01.class) { a -= 1; System.out.println(i + 'td2:=' + a);} }} }; public static void main(String[] args) {Thread01 th = new Thread01();th.td1.start();th.td2.start(); }}
某次运行结果:
(td1 出现的地方,a 就 +1;td2 出现的地方,a 就 -1)
相关文章:
1. python相关问题求解决,有偿2. javascript - input输入框触发change事件后,外部元素会被选中3. python - 用__call__ 实现装饰器功能4. javascript - 把字符串日期转换成一般时间格式后,发现小于10的数字不会自动添加0在前面,如下5. javascript - 在sublime中如何给.vue文件注释?6. javascript - js判断一个数组是否重复7. python - 请问用cxfreeze打包的可执行程序能反编译出源码么?8. javascript - vue2.0中router.repalce跟router.push有什么区别,二者的应用场景是会有怎样的区别?9. javascript - 这种上传图片预览怎么做?10. javascript - prismplayer播放器全屏问题