高并发编程学习笔记二:
1. reentrantlock 重入锁
1. reentrantlock可以实现与synchronized一样的功能,synchronized在发生异常的时候,jvm会自动释放锁。但是reentrantlock必须手动释放锁。通常在finally中释放锁。
public class Demo1 {
Lock lock = new ReentrantLock();
void m1(){
lock.lock();//锁定
try {
for (int i = 0; i < 10; i++) {
System.out.println(i);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
lock.unlock();//释放
}
}
void m2(){
lock.lock();
System.out.println("m2...");
lock.unlock();
}
public static void main(String[] args){
Demo1 demo1 = new Demo1();
new Thread(()->demo1.m1()).start();
new Thread(()->demo1.m2()).start();
}
}
2. reentrantlock可以尝试锁定,根据锁定是否成功来决定执行什么代码
public class Demo2 {
Lock lock = new ReentrantLock();
void m1(){
lock.lock();
try{
for(int i = 0;i<10;i++){
System.out.println(i);
TimeUnit.SECONDS.sleep(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
void m2(){
boolean locked = false;
try {
locked = lock.tryLock(5,TimeUnit.SECONDS);//连续5s尝试锁定,5s之后返回结果
if(locked){
System.out.println("m2 get locked");
}else System.out.println("m2 can not lock");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (locked) lock.unlock(); //释放锁的时候判断 如果锁定了就释放锁
}
}
public static void main(String[] args){
Demo2 demo2 = new Demo2;
new Thread(()->demo2.m1()).start();
new Thread(()->demo2.m2()).start();
}
}
3. reentrantlock.lockInterruptibly() 更灵活可以接受中断信号,主线程可以调用Thread.interrupt()来打断线程。synchronized或者renentratlock.lock()均无法接收中断信号。
public class Demo3 {
public static void main(String[] args){
Lock lock = new ReentrantLock();
Thread t1 = new Thread(()->{
try {
lock.lock();
System.out.println("t1 start ");
TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
} catch (InterruptedException e) {
System.out.println("t1 is interrupted");
} finally {
lock.unlock();
}
});
Thread t2 = new Thread(()->{
try {
lock.lockInterruptibly();
System.out.println("m2........");
} catch (InterruptedException e) {
System.out.println("t2 is interrupted");
} finally {
if(lock.tryLock())lock.unlock();
}
});
t1.start();
t2.start();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.interrupt();
}
}
4. reentrantlock可以被指定为公平锁,synchronized是不公平锁:指的是当多个线程同时在等待某一个资源的时候,当资源空闲时,线程调度器会随机选择一个线程锁定该资源,不考虑线程等待的时间。公平锁就是谁等的时间长谁就可以获取这个资源。 公平锁效率比较低。
public class Demo4 {
private static ReentrantLock reentrantLock = new ReentrantLock(true);
public void m(){
for (int i=0;i<100;i++){
try {
reentrantLock.lock();
System.out.println(Thread.currentThread().getName() + " get lock");
}finally {
reentrantLock.unlock();
}
}
}
public static void main(String[] args){
Demo4 demo4 = new Demo4();
Thread t1 = new Thread(()->demo4.m(),"t1");
Thread t2 = new Thread(()->demo4.m(),"t2");
t1.start();
t2.start();
}
}
result:t2 get lock
t1 get lock
t2 get lock
t1 get lock
面试题:设计一个同步容器,提供put与get方法。同步容器最大容量为10,两个线程负责生产,十个线程负责消费 1. 用wait与notifyAll实现
public class DemoTest1 {
private LinkedList<Object> container = new LinkedList<>();
private int SIZE = 10;
private int count = 0;
private synchronized void put(Object o){
while (container.size() == SIZE){//为什么用while不用if
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
container.add(o);
System.out.println("put methord container size : " + container.size());
count++;
this.notifyAll();//为什么用notifyAll不用notify
}
private synchronized Object get(){
Object o = null;
while (container.size() == 0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
o = container.removeFirst();
count--;
System.out.println("get methord container size : " + (container.size()-1));
this.notifyAll();
return o;
}
public static void main(String[] args){
DemoTest1 test1 = new DemoTest1();
//消费者线程
for(int i=0;i<10;i++){
new Thread(()->{
for(int j = 0 ; j<5; j++){
test1.get();
}
}).start();
}
//生产者线程
for(int i = 0 ; i < 2 ; i++){
new Thread(()->{
for(int j = 0 ; j<25; j++){
test1.put(new Object());
}
}).start();
}
}
}
1. 为什么用while不用if:线程从哪里wait就从哪里醒来,当notifyAll被调用时,所有线程处于就绪状态,确实此时只有一个线程先拿到锁。但是第一个线程执行完之后,释放锁,第二个线程拿到锁。如果第二个线程是用的if,那么从这里唤醒 。直接就又add/get了一个就出问题了,所以要用while ,while在被唤醒跳出循环的时候会再次进行判断,是否满足条件。这样就避免了异常的出现。** wait大部分时间与while一起使用
2. 为什么用notifyAll不用notify:这个容器只有一把锁,也就是说,生产者消费者同时用一个锁,假如生产者线程put完之后,容器容量达到上限,此时用notify恰巧唤醒了另一个生产者容器,此时该生产者线程wait,会释放锁,但是没有线程被唤醒,没有线程申请这把锁,所以这个程序就停止了。所有用notifyAll。
2. 用condition和lock:用wait与notifyAll效率比较低,不能按类型唤醒。用condition可以按照类型唤醒,精准唤醒。
public class DemoTest1 {
private LinkedList<Object> container = new LinkedList<>();
private int SIZE = 10;
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
private Condition producter = lock.newCondition();
private Condition consumer = lock.newCondition();
private void put(Object o){
try {
lock.lock();
while (container.size() == SIZE){
producter.await();//生产者等待
}
container.add(o);
System.out.println("put methord container size : " + container.size());
count++;
consumer.signalAll();//消费者唤醒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
private Object get(){
try {
lock.lock();
Object o = null;
while (container.size() == 0){
consumer.await();//消费者等待
}
o = container.removeFirst();
count--;
System.out.println("get methord container size : " + container.size());
producter.signalAll();
return o;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
public static void main(String[] args){
DemoTest1 test1 = new DemoTest1();
//消费者线程
for(int i=0;i<10;i++){
new Thread(()->{
for(int j = 0 ; j<5; j++){
test1.get();
}
}).start();
}
//生产者线程
for(int i = 0 ; i < 2 ; i++){
new Thread(()->{
for(int j = 0 ; j<25; j++){
test1.put(new Object());
}
}).start();
}
}
}
2. ThreadLocal:是指线程的局部变量。只有自己的线程可以访问修改,别的线程看不到,自己改自己的。就相当于每一个threadlocal都是一个类,每一个线程都用这个类生成了一个自己的threadlocal对象。所以说这就是threadlocal的global&local。谁都可以访问,但是自己搞自己的。
public class Demo5 {
static ThreadLocal<test> threadLocal = new InheritableThreadLocal<>();
public static void main(String[] args){
new Thread(()->{
threadLocal.set(new test());
System.out.println("t1 : "+ threadLocal.get().getName());
},"t1").start();
new Thread(()->{
System.out.println("t2 : "+ (threadLocal.get()==null?null:threadLocal.get().getName()));
},"t2").start();
}
static class test{
private String name;
public test(){
name = "test name";
}
public String getName() {
return name;
}
}
}
result:t2 : null
t1 : test name