多線程使用技巧

1. 多個線程互相等待

//引入包
import java.util.concurrent.CountDownLatch;



//代碼
        int THREAD_COUNT = 2;
        final CountDownLatch latch = new CountDownLatch(THREAD_COUNT);
        Thread[] threads = new Thread[THREAD_COUNT];
        threads[0] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                   //todo
                } catch (Exception e) {
                    System.out.println(e + "");
                    LOGGER.error("執行失敗", e);
                } finally {
                    latch.countDown();
                }
            }
        });
        threads[0].start();
        threads[1] = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //todo
                } catch (Exception e) {
                    LOGGER.error("執行失敗", e);
                } finally {
                    latch.countDown();
                }
            }
        });
        threads[1].start();
        try {
            latch.await();
        } catch (Exception e) {
            LOGGER.error("執行失敗", e);
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章