• 多线程_线程插队_join()方法与锁的释放


    线程插队

            线程执行join()方法后,其他线程将会等待该线程终止后再执行

            若给join()方法添加参数,则效果为:仅允许该线程插队参数毫秒

    锁的释放

            join()方法对于锁的释放,在不同的情况下会有不同的表现

            先说结论:join()方法只会释放被调用线程的对象锁

    情景一:String对象被上锁,锁为String的对象锁

    1. package cn.alan.threadState;
    2. //测试插队线程
    3. public class TestJoin implements Runnable{
    4. String hello;
    5. public TestJoin(String hello) {
    6. this.hello = hello;
    7. }
    8. @Override
    9. public void run() {
    10. synchronized (hello){
    11. for (int i = 0; i < 5; i++) {
    12. System.out.println("插队线程执行" + hello);
    13. }
    14. }
    15. }
    16. public static void main(String[] args) throws InterruptedException {
    17. String hello = "hello";
    18. //启动插队线程
    19. Thread thread = new Thread(new TestJoin(hello));
    20. thread.start();
    21. synchronized (hello){
    22. //主线程
    23. for (int i = 0; i < 10; i++) {
    24. if (i==5){
    25. thread.join();
    26. }
    27. System.out.println("主线程执行" + hello);
    28. }
    29. }
    30. }
    31. }

            可以看到join()方法并不能释放String的对象锁,主线程与子线程之间发生死锁,只能手动停止程序

    情景二:直接对子线程对象上锁,锁为子线程的对象锁

    1. //测试插队线程
    2. public class TestJoin implements Runnable{
    3. String hello;
    4. public TestJoin(String hello) {
    5. this.hello = hello;
    6. }
    7. @Override
    8. public void run() {
    9. synchronized (this){
    10. for (int i = 0; i < 5; i++) {
    11. System.out.println("插队线程执行" + hello);
    12. }
    13. }
    14. }
    15. public static void main(String[] args) throws InterruptedException {
    16. String hello = "hello";
    17. //启动插队线程
    18. Thread thread = new Thread(new TestJoin(hello));
    19. thread.start();
    20. synchronized (thread){
    21. //主线程
    22. for (int i = 0; i < 10; i++) {
    23. if (i==5){
    24. thread.join();
    25. }
    26. System.out.println("主线程执行" + hello);
    27. }
    28. }
    29. }
    30. }

            可以看到子线程的对象锁被释放,程序有序运行,未发生死锁

    原因探究

    从源码不难看出,join()方法本身被加上了synchronized锁,即Thread的对象锁。故在join()方法中调用wait(),仅会释放Thread的对象锁

  • 相关阅读:
    【MySQL】导入 JSONL 数据到 MySQL数据库
    三位大咖的「研发效能」实战笔记|大师课精华全回顾
    Mac OS 使用远程桌面登录服务器
    30m退耕还湿空间数据集(2000-2010年,西南地区)
    从餐桌到太空,孙宇晨的“星辰大海”
    Node+koa项目实战之项目初始化
    Spring Boot Security使用 JDBC 和 MySQL 进行 RBAC,自定义登录验证,登录界面增加kaptcha验证码
    6-1 选择排序
    clion安装C++远程linux开发并调试 从装centos虚拟机到完美开发调试
    【项目管理冲刺-必会概念】
  • 原文地址:https://blog.csdn.net/Mudrock__/article/details/126239610