自学内容网 自学内容网

主线程结束子线程不再执行

问题背景:

起因是在做分布式锁的时候,我在单元测试里面创建了10个线程,然后启动。每个线程都会在run方法打印内容,但是测试结果居然什么都没输出。就很纳闷,然后推测可能是主线程执行完了子线程直接结束了,果不其然,在加上thread.join()得到了预期结果。

问题结论:

如果是写在main方法是不存在这个问题的,但是单测的确存在这个问题。

问题过程:

原始代码:

@Test
    public void multipleThreadTest(){
        System.out.println(Thread.currentThread().getName());
        LockThread[] lockThreads = new LockThread[10];
        for (int i=0;i< lockThreads.length;i++){
            lockThreads[i] = new LockThread(new ZkNodeNoneBlockingLock("app"));
        }
        for (LockThread lockThread : lockThreads) {
            lockThread.start();
        }
    }

    private static class LockThread extends Thread{
        ZkNodeNoneBlockingLock locker;
        public LockThread(ZkNodeNoneBlockingLock locker){
            this.locker = locker;
        }
        @Override
        public void run() {
            boolean lock = locker.lock();
            System.out.println(this.getName() + (lock ? "上锁成功" : "上锁失败"));
        }
    }

修改后代码:

@Test
    public void multipleThreadTest(){
        System.out.println(Thread.currentThread().getName());
        LockThread[] lockThreads = new LockThread[10];
        for (int i=0;i< lockThreads.length;i++){
            lockThreads[i] = new LockThread(new ZkNodeNoneBlockingLock("app"));
        }
        for (LockThread lockThread : lockThreads) {
            lockThread.start();
        }
        for (LockThread lockThread : lockThreads){
            try {
                lockThread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static class LockThread extends Thread{
        ZkNodeNoneBlockingLock locker;
        public LockThread(ZkNodeNoneBlockingLock locker){
            this.locker = locker;
        }
        @Override
        public void run() {
            boolean lock = locker.lock();
            System.out.println(this.getName() + (lock ? "上锁成功" : "上锁失败"));
        }
    }

注释:

thread.join()是当前线程,也就是main线程要等到thread线程执行完成才能继续往后执行。


原文地址:https://blog.csdn.net/m0_59925573/article/details/140254674

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!