java多线程的原子性


class Count {
	public int num;

	public synchronized void increment() {
		num++;
	}

	public int get() {
		return num;
	}
}

public class ThreadDemo1 {
	public static void main(String[] args) {
		final Count count = new Count();
		Runnable runnable = new Runnable() {
			public void run() {
				for (int i = 0; i < 15000; i++) {
//					 System.out.println("i:------" + i + ">>>>>>>>>>>>"
//						+ Thread.currentThread().getName());
					count.increment();
				}
			}
		};
		List<Thread> threads = new ArrayList<>(10);
		for (int i = 0; i < 10; i++) {
			Thread thread = new Thread(runnable);
			threads.add(thread);
			thread.start();
		}
		while (true) {
			if (allThreadTerminated(threads)) {// 所有线程运行结束
				System.out.println(count.get());
				break;
			}
		}
	}

	private static boolean allThreadTerminated(List<Thread> threads) {
		for (Thread thread : threads) {
			if (thread.isAlive()) {
				return false;
			}
		}
		return true;
	}
}

以上代码开了十个线程对num++;操作
原來我一直以为一句代码就是原子性了,今天从学长处得知原子性不是我想的那样,所以看了一下资料发现:

原子操作 :就是不可再分的操作

1.以下多线程对int型变量x的操作,哪几个需要进行同步:( )
A. x=y; B. x++; C. ++x; D. x=1;
D是原子的,不管几个线程调用都是返回赋值后的x
B C都不算是原子的,因为别的线程如果调用x的话可能得到没有被赋值的x
A为原子的但不满足 可见性(Visibility)


2.对于非int类型的变量在赋值时可以使用volatile来保证赋值的时候的原子性


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值