线程通信轮询
輪詢方式
輪詢,可以實現線程通信
package com.bjsxt.base.conn008;import java.util.ArrayList; import java.util.List;public class ListAdd1 {private volatile static List list = new ArrayList();public void add() {list.add("bjsxt");}public int size() {return list.size();}public static void main(String[] args) {final ListAdd1 list1 = new ListAdd1();Thread t1 = new Thread(new Runnable() {@Overridepublic void run() {try {for (int i = 0; i < 10; i++) {list1.add();System.out.println("當前線程:" + Thread.currentThread().getName() + "添加了一個元素..");Thread.sleep(500);}} catch (InterruptedException e) {e.printStackTrace();}}}, "t1");Thread t2 = new Thread(new Runnable() {@Overridepublic void run() {while (true) {if (list1.size() == 5) {System.out.println("當前線程收到通知:" + Thread.currentThread().getName() + " list size = 5 線程停止..");throw new RuntimeException();}}}}, "t2");t1.start();t2.start();}}運行
線程t1,向list添加元素
線程t2,輪詢檢查list元素個數
當list中有5個元素的時候,執行相應代碼
總結
- 上一篇: 线程通信wait与notify
- 下一篇: CountDownLatch实时通信