• 多线程_线程插队_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的对象锁

  • 相关阅读:
    爱上开源之golang入门至实战第四章函数(Func)(二)
    uni-app基于vue实现商城小程序
    Linux禁用退格键的响铃
    MySQL - InnoDB记录结构
    SDUT—Python程序设计实验五(列表与元组)
    【JUC】循环屏障 CyclicBarrier 详解
    Java Object 类
    开源项目丨ChengYing 1.1版本重磅发布:新增超多功能,全新优化体验!
    技嘉主板前置面板没有声音的解决
    系统架构设计:20 论软件需求管理
  • 原文地址:https://blog.csdn.net/Mudrock__/article/details/126239610