欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java CountDownLatch与golang WaitGroup的用法

程序员文章站 2024-01-09 23:08:46
主线程等待所有线程执行结束再继续执行public class TestCountDownLatch { static int loopCount = 10; static CountDownLatch latch = new CountDownLatch(loopCount); static class Hello implements Runnable{ private int i; private Hello(int i){...

主线程等待所有线程执行结束再继续执行

public class TestCountDownLatch {

    static int loopCount = 10;
    static CountDownLatch latch = new CountDownLatch(loopCount);

    static class Hello implements Runnable{

        private int i;

        private Hello(int i){
            this.i = i;
        }

        @Override
        public void run() {
            System.out.println("hello i = "+i);
            latch.countDown();
        }
    }

    public static void main(String[] args) throws Exception {
        for(int i = 0; i < loopCount; i++){
            new Thread(new Hello(i)).start();
        }
        latch.await();
        System.out.println("main finish");
    }
}
var wg sync.WaitGroup

func hello(i int) {
	defer wg.Done()
	fmt.Println("hello i = ", i)
}

func main() {
	loopCount := 10
	wg.Add(loopCount)
	for i := 0; i < loopCount; i++ {
		go hello(i)
	}
	wg.Wait()
	fmt.Println("main finish")
}

本文地址:https://blog.csdn.net/lovecj111/article/details/110290098