JUC-- synchronized锁 以及 lock锁

JUC-- synchronized锁 以及 lock锁,第1张

JUC-- synchronized锁 以及 lock锁

一段代码说明锁的作用

public class Test {
	
	private static int a;

	private static int b;

	private static int c;
	
	static Lock lock = new ReentrantLock();
	private synchronized static void incrOfa() {
		a++;
	}
	private static void incrOfb() {
		b++;
	}
	private static void incrOfc() {
		lock.lock();
		c++;
		lock.unlock();
	}
	
	public static void main(String[] args) {
		ExecutorService executor = Executors.newCachedThreadPool();
		CountDownLatch downLatch = new CountDownLatch(10000);
		for (int i = 0; i < 10000; i++) {
			executor.execute(() ->{
				incrOfa();
				incrOfb();
				incrOfc();
				downLatch.countDown();
			});
		}
		try {
			downLatch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executor.shutdown();
		System.out.println("synchronized锁:"+a);
		System.out.println("无锁:"+b);
		System.out.println("lock锁 :"+c);
	}
}

synchronized锁:10000
无锁:9994
lock锁 :10000

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5705920.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存