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

线程插队

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

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

锁的释放

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

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

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

package cn.alan.threadState;

//测试插队线程
public class TestJoin implements Runnable{
    String hello;

    public TestJoin(String hello) {
        this.hello = hello;
    }

    @Override
    public void run() {
        synchronized (hello){
            for (int i = 0; i < 5; i++) {
                System.out.println("插队线程执行" + hello);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String hello = "hello";

        //启动插队线程
        Thread thread = new Thread(new TestJoin(hello));
        thread.start();

        synchronized (hello){
            //主线程
            for (int i = 0; i < 10; i++) {
                if (i==5){
                    thread.join();
                }
                System.out.println("主线程执行" + hello);
            }
        }

    }
}

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

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

//测试插队线程
public class TestJoin implements Runnable{
    String hello;

    public TestJoin(String hello) {
        this.hello = hello;
    }

    @Override
    public void run() {
        synchronized (this){
            for (int i = 0; i < 5; i++) {
                System.out.println("插队线程执行" + hello);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        String hello = "hello";

        //启动插队线程
        Thread thread = new Thread(new TestJoin(hello));
        thread.start();

        synchronized (thread){
            //主线程
            for (int i = 0; i < 10; i++) {
                if (i==5){
                    thread.join();
                }
                System.out.println("主线程执行" + hello);
            }
        }

    }
}

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

原因探究

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值