用wait和notify来实现线程之间的通信,这两个方法是object方法,这两个方法必须要配合synchronized使用。wait方法释放锁,notify不释放锁。
原始线程通信方式
1 import java.util.ArrayList; 2 import java.util.List; 3 4 public class ListAdd1 { 5 6 7 private volatile static List list = new ArrayList(); 8 9 public void add(){ 10 list.add("bjsxt"); 11 } 12 public int size(){ 13 return list.size(); 14 } 15 16 public static void main(String[] args) { 17 18 final ListAdd1 list1 = new ListAdd1(); 19 20 Thread t1 = new Thread(new Runnable() { 21 @Override 22 public void run() { 23 try { 24 for(int i = 0; i <10; i++){ 25 list1.add(); 26 System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素.."); 27 Thread.sleep(500); 28 } 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 } 33 }, "t1"); 34 35 Thread t2 = new Thread(new Runnable() { 36 @Override 37 public void run() { 38 while(true){ 39 if(list1.size() == 5){ 40 System.out.println("当前线程收到通知:" + Thread.currentThread().getName() + " list size = 5 线程停止.."); 41 throw new RuntimeException(); 42 } 43 } 44 } 45 }, "t2"); 46 47 t1.start(); 48 t2.start(); 49 } 50 51 52 }