https://blog.csdn.net/weixin_43888181/article/details/116546374?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522164493673916780271597016%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=164493673916780271597016&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allbaidu_landing_v2~default-4-116546374.first_rank_v2_pc_rank_v29&utm_term=java+juc&spm=1018.2226.3001.4187
https://www.bilibili.com/video/BV1Kw411Z7dF?from=search&seid=16637953733327750371&spm_id_from=333.337.0.0
使用锁来保证代码只有一个线程在执行,代替synchronized关键字
建议看以上两个引用
//true表示为公平锁 锁对于每个线程都是公平的 效率比较低
//flase表示为非公平锁 锁对于每个线程都是非公平的 容易造成线程饿死的情况 效率比较高
//new了一个可重入锁
private final ReentrantLock lock = new ReentrantLock(true);
@Test
public void test1(){
try {
lock.lock();
System.out.println("11");
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
读写锁
有关于写的操作都会线程都会阻塞运行,而读不受影响
package com.example.demo.test;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@Controller
public class fffw {
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
@RequestMapping("/read123")
@ResponseBody
public String read(){
lock.readLock().lock();
try {
//读执行操作要1秒种
// TimeUnit.SECONDS.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.readLock().unlock();
}
return "ok";
}
@RequestMapping("/write123")
@ResponseBody
public String write(){
lock.writeLock().lock();
try {
//写执行操作要5秒种
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.writeLock().unlock();
}
return "ok";
}
}