package com.brendan.cn.concurrent;
import java.util.concurrent.locks.ReentrantLock;
public class ReenterLock implements Runnable {
public static ReentrantLock lock = new ReentrantLock();
public static int i = 0;
@Override
public void run() {
for (int j = 0; j <10000 ; j++) {
lock.lock();
try {
i ++;
System.out.println((Thread.currentThread().getName() +" === > "+i));
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
ReenterLock rl = new ReenterLock();
Thread t1 = new Thread(rl);
Thread t2 = new Thread(rl);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("*************"+i);
}
}
这里的join 指的是加入一个线程,t.join 指等待t1线程执行完后,主线程才执行
重入锁的重入是指一个线程可以多次获取资源
重入锁 (替换synchronized)
最新推荐文章于 2023-10-05 23:04:06 发布