Thinking in Java学习笔记 Lock在处理结构上的优越性,相对于synchronized

本文详细介绍了并发编程中Lock和synchronized两种锁机制的使用方式,包括如何在finally语句中优雅地释放锁,以及如何使用tryLock方法限时获取锁。同时对比了两者在异常处理上的差异,提供了实用的编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Lock使用时,使用try..finally..语句,在finally中Lock.unLock来释放锁,同时可以在处理失败的情况下,在finally语句中做优雅的处理

而synchronized语句则无法优雅的结束,发生异常直接退出了

同时,还可以使用tryLock(int x, TimeUnit timeunit)的方法来限时获取锁,获取失败可以做其他事情

package com.test.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MutexEvenGenerator extends EvenGenerator implements Runnable{
	public MutexEvenGenerator(IntGenerator ig){
		this.ig=ig;
		gtest=new GeneratorTester(ig);
	}
	IntGenerator ig;
	GeneratorTester gtest;
	@Override
	public void run(){
		gtest.test();
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ExecutorService exec=Executors.newCachedThreadPool();
		IntGenerator ig=new EvenGenerator();
		for(int i=0;i<10;i++){
			exec.execute(new MutexEvenGenerator(ig));
		}
	}

}
interface IntGenerator{
	int next();
	boolean isCanceled();
	void cancel();
}
class EvenGenerator implements IntGenerator{
	int num=0;
	boolean canceled=false;
	Lock lock=new ReentrantLock();
	public int next(){
		<span style="color:#ff0000;">try{
			lock.lock();
			num++;
			Thread.yield();
			num++;
			return num;
		}finally{
			lock.unlock();
		}</span>
	}
	public boolean isCanceled(){
		return canceled;
	}
	public void cancel(){
		canceled=true;
	}
}
class GeneratorTester{
	private IntGenerator ig;
	public GeneratorTester(IntGenerator ig){
		this.ig=ig;
	}
	public void test(){
		int v;
		while(ig.isCanceled()==false){
			v=ig.next();
			if(v%2!=0){
				System.out.println("generate even error value:"+v);
				ig.cancel();
				return;
			}
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值