其他分享
首页 > 其他分享> > 重入锁基础代码

重入锁基础代码

作者:互联网

//ReentrantLock是一个类
//里面有很多方法
//比如lock,lockInterruptibly,tryLock,tryLock(参数,参数),unlock
import java.util.concurrent.locks.ReentrantLock;
public class ReenterLock implements Runnable{
	//ReentrantLock中文名叫重入锁
	public static ReentrantLock lock = new ReentrantLock();
	public static int i = 0;
	@Override
	public void run(){
		for(int j = 0;j<1000000;j++){
			//一个线程可以同时获得两把锁
			//所以叫做重入锁
			//但记住放锁的次数要和加锁的次数相同
			//你也可以各去掉一个
			lock.lock();
			lock.lock();
			try{
				i++;
			}finally{
				lock.unlock();
				lock.unlock();
			}
		}
	} 
	public static void main(String[] args) throws InterruptedException{
		ReenterLock t = new ReenterLock();
		Thread t1 = new Thread(t);
		Thread t2 = new Thread(t);
		t1.start();
		t2.start();
		t1.join();
		t2.join();
		System.out.println(i);

	
		
	}
}

标签:重入,int,lock,代码,ReentrantLock,基础,static,tryLock,public
来源: https://blog.csdn.net/qq_43776408/article/details/98041245