多线程丢失更新、加锁

1.不加锁的情况

package test.thread;

import java.util.concurrent.locks.ReentrantLock;

public class TestSyncCurrent {

	public static void main(String[] args) {

		Shop shop = new Shop();
		
		Runnable r1 = new Client(shop, 500);
		Runnable r2 = new Client(shop, 1000);
		Runnable r3 = new Client(shop, 1500);
		Runnable r4 = new Client(shop, 500);
		Runnable r5 = new Client(shop, 1000);
		Runnable r6 = new Client(shop, 1500);
		
		new Thread(r1).start();
		new Thread(r2).start();
		new Thread(r3).start();
		new Thread(r4).start();
		new Thread(r5).start();
		new Thread(r6).start();
		new Thread(r1).start();
		new Thread(r2).start();
		new Thread(r3).start();
		System.out.println("main:" + Thread.currentThread().getName());
	}
	
	public static class Shop{
		ReentrantLock lock = new ReentrantLock();
		private int count = 0;
		//volatile int count = 0;
		
		public int add(long delay){
			try {
				System.out.println(Thread.currentThread().getName() + ":add:start:");
				//lock.lock();
				Thread.sleep(delay);
				count ++;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally{
				//lock.unlock();
				System.out.println(Thread.currentThread().getName() + ":add:end:");
			}
			return count;
		}
	}
	
	public static class Client implements Runnable {
		
		private Shop shop;
		private long delay;
		
		public Client(Shop shop, long delay) {
			this.shop = shop;
			this.delay = delay;
		}

		@Override
		public void run() {
			for(int i=0; i<10; i++) {
				try {
					//Thread.sleep(500);
					int ret = shop.add(delay);
					System.out.println("result:" + ret);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}

9 个线程,每个线程运行10次,count结果应该是 90,实验大致结果: 60 < count < 88 浮动, 运行时间约为: 15秒

2. count 使用 volatile 修饰 结果 与 1 大致相同,求解释哪里出问题了。

3. ReentrantLock 加锁后,结果正确,运行时间: 90秒

具体结果正在分析中。

转载于:https://my.oschina.net/gofan/blog/77173

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值