java多線程學習之通過輪詢實現線程通信

package learn.thread;

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

/*
 * 線程通信-輪詢方式
 */
public class Demo10 {

    public static List<Object> os = new ArrayList<Object>();

    public static void main(String[] args) {

        Thread t1 = new Thread() {

            @Override
            public void run() {
                System.out.println("線程1啓動");
                for (int i = 0; i < 10; i++) {
                    os.add(new Object());
                    System.out.println("添加一個元素");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("線程1完成任務退出");
            }

        };
        Thread t2 = new Thread() {

            @Override
            public void run() {
                System.out.println("線程2啓動");
                while (true) {
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(os.size());
                    if (os.size() == 5) {
                        System.out.println("執行線程2業務");
                        break;
                    }
                }
                System.out.println("線程2完成任務退出");
            }

        };
        t1.start();
        t2.start();

    }

}
// 線程2啓動
// 線程1啓動
// 添加一個元素
// 1
// 1
// 1
// 添加一個元素
// 2
// 2
// 2
// 添加一個元素
// 3
// 3
// 3
// 添加一個元素
// 4
// 4
// 4
// 4
// 添加一個元素
// 5
// 執行線程2業務
// 線程2完成任務退出
// 添加一個元素
// 添加一個元素
// 添加一個元素
// 添加一個元素
// 添加一個元素
// 線程1完成任務退出
發佈了49 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章