Java实现主线程等待子线程

本文介绍两种主线程等待子线程的实现方式,以5个子线程来说明:

1、使用Thread的join()方法,join()方法会阻塞主线程继续向下执行。

2、使用java.util.concurrent中的CountDownLatch,是一个倒数计数器。初始化时先设置一个倒数计数初始值,每调用一次countDown()方法,倒数值减一,他的await()方法会阻塞当前进程,直到倒数至0。

join方式代码如下:

package com.test.thread;

import java.util.ArrayList;
import java.util.List;

public class MyThread extends Thread
{

    public MyThread(String name)
    {
        this.setName(name);
    }

    @Override
    public void run()
    {
        System.out.println(this.getName() + " staring...");

        System.out.println(this.getName() + " end...");
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        System.out.println("main thread starting...");

        List<MyThread> list = new ArrayList<MyThread>();

        for (int i = 1; i <= 5; i++)
        {
            MyThread my = new MyThread("Thrad " + i);
            my.start();
            list.add(my);
        }

        try
        {
            for (MyThread my : list)
            {
                my.join();
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        System.out.println("main thread end...");

    }

}
运行结果如下:

main thread starting...
Thrad 2 staring...
Thrad 2 end...
Thrad 4 staring...
Thrad 4 end...
Thrad 1 staring...
Thrad 1 end...
Thrad 3 staring...
Thrad 3 end...
Thrad 5 staring...
Thrad 5 end...
main thread end...
CountDownLatch方式代码如下:

package com.test.thread;

import java.util.concurrent.CountDownLatch;

public class MyThread2 extends Thread
{

    private CountDownLatch count;

    public MyThread2(CountDownLatch count, String name)
    {
        this.count = count;
        this.setName(name);
    }

    @Override
    public void run()
    {
        System.out.println(this.getName() + " staring...");

        System.out.println(this.getName() + " end...");
        this.count.countDown();
    }

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        System.out.println("main thread starting...");

        CountDownLatch count = new CountDownLatch(5);

        for (int i = 1; i <= 5; i++)
        {
            MyThread2 my = new MyThread2(count, "Thread " + i);
            my.start();
        }

        try
        {
            count.await();
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }

        System.out.println("main thread end...");

    }

}

运行结果如下:

main thread starting...
Thread 2 staring...
Thread 2 end...
Thread 4 staring...
Thread 4 end...
Thread 1 staring...
Thread 1 end...
Thread 3 staring...
Thread 3 end...
Thread 5 staring...
Thread 5 end...
main thread end...


  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中,线程等待线程可以使用CountDownLatch或者LockSupport实现。其中CountDownLatch是一个同步工具类,可以让一个或多个线程等待其他线程完成操作,而LockSupport则是一个线程阻塞工具类,可以让线程阻塞和唤醒。 使用CountDownLatch实现线程等待线程的示例代码如下: ```java import java.util.concurrent.CountDownLatch; public class Main { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(2); // 创建CountDownLatch对象,计数器初始值为2 new Thread(() -> { try { System.out.println("线程1开始执行"); Thread.sleep(2000); // 模拟线程1执行任务 System.out.println("线程1执行完毕!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); // 计数器减1 } }).start(); new Thread(() -> { try { System.out.println("线程2开始执行"); Thread.sleep(3000); // 模拟线程2执行任务 System.out.println("线程2执行完毕!"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); // 计数器减1 } }).start(); latch.await(); // 线程等待计数器归零 System.out.println("线程执行!\ndo something..."); } } ``` 使用LockSupport实现线程等待线程的示例代码如下: ```java import java.util.concurrent.locks.LockSupport; public class Main { public static void main(String[] args) { Thread mainThread = Thread.currentThread(); new Thread(() -> { try { System.out.println("线程开始执行"); Thread.sleep(2000); // 模拟线程执行任务 System.out.println("线程执行完毕!"); } catch (InterruptedException e) { e.printStackTrace(); } LockSupport.unpark(mainThread); // 唤醒线程 }).start(); LockSupport.park(); // 线程阻塞 System.out.println("线程执行!\ndo something..."); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值