首页 > 其他分享 >Lock锁(性能更好,是代码块锁,synchronized锁能锁方法)

Lock锁(性能更好,是代码块锁,synchronized锁能锁方法)

时间:2023-03-07 19:33:35浏览次数:30  
标签:testLock2 TestLock2 synchronized Thread lock start Lock new 锁能

package com.Java;

import java.util.concurrent.locks.ReentrantLock;

//可重入锁
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}

class TestLock2 extends Thread {
int stickNum = 100;
private ReentrantLock lock = new ReentrantLock();

@Override
public void run() {
while (true) {
lock.lock(); //锁住
if (stickNum > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();//释放锁
}
System.out.println(stickNum--);
}
}
}
}

标签:testLock2,TestLock2,synchronized,Thread,lock,start,Lock,new,锁能
From: https://www.cnblogs.com/fc666/p/17189319.html

相关文章