1. 程式人生 > >Join與CountDownLatch之間的區別

Join與CountDownLatch之間的區別

Join與CountDownLatch之間的區別

import java.util.concurrent.CountDownLatch;

public class CountDownLatchTest {
    public static CountDownLatch c = new CountDownLatch(2);
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(1);
                c.countDown();
                System.out.println(2);
                c.countDown();
            }
        });
        t.start();
        c.await();
        System.out.println(3);
    }
}

點選檢視結果

1
2
3
public class JoinCountDownLatchTest {
    public static void main(String[] args) throws InterruptedException {
        
        Thread parse1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("parse1 finish!");
            }
        });
        
        Thread parse2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("parse2 finish!");
            }
        });
        
        parse1.start();
        parse2.start();
        parse1.join();
        parse2.join();
        System.out.println("all parse finish!");
    }
}

點選檢視結果

parse1 finish!
parse2 finish!
all parse finish!
或者
parse2 finish!
parse1 finish!
all parse finish!