多线程学习二十二:多把锁

2021/5/9 18:56:04

本文主要是介绍多线程学习二十二:多把锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

多把锁

一间大屋子有两个功能:睡觉、学习,互不相干。现在小南要学习,小女要睡觉,但如果只用一间屋子(一个对象锁)的话,那么并发度很低. 解决方法是准备多个房间(多个对象锁)

@Slf4j(topic = "c.test27:")
public class Test27 {
    public static void main(String[] args) {
        BigRoom bigRoom = new BigRoom();
        new Thread(() -> {
            try {
                bigRoom.study();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "小南").start();
        new Thread(() -> {
            try {
                bigRoom.sleep();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "小女").start();
    }
}
//共享资源
class BigRoom {
    public void sleep() throws InterruptedException {
        synchronized (this) {
            log.debug("sleeping 2 小时");
            TimeUnit.SECONDS.sleep(2);
        }
    }
    public void study() throws InterruptedException {
        synchronized (this) {
            log.debug("study 1 小时");
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

改进后

  • 将锁的粒度细分
  • 好处,是可以增强并发度
  • 坏处,如果一个线程需要同时获得多把锁,就容易发生死锁
class BigRoom {
    private final Object studyRoom = new Object();
    private final Object bedRoom = new Object();

    public void sleep() throws InterruptedException {
        synchronized (bedRoom) {
            log.debug("sleeping 2 小时");
            TimeUnit.SECONDS.sleep(2);
        }
    }
    public void study() throws InterruptedException {
        synchronized (studyRoom) {
            log.debug("study 1 小时");
            TimeUnit.SECONDS.sleep(1);
        }
    }
}


这篇关于多线程学习二十二:多把锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程