关于wait和notify的问题
香蕉波波球 2017-12-10 12:38:46 package com.bjsxt.base.conn008;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
/**
* @author wangyang
*
*/
public class ListAdd2 {
private volatile static List list = new ArrayList();
public void add(){
list.add("wangyang");
}
public int size(){
return list.size();
}
public static void main(String[] args) throws InterruptedException {
final ListAdd2 list2 = new ListAdd2();
final Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
synchronized (lock) {
System.out.println("t1启动..");
for(int i = 0; i <10; i++){
list2.add();
System.out.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素..");
Thread.sleep(500);
if(list2.size() == 5){
System.out.println("已经发出通知..");
lock.notify();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(list2.size());
synchronized (lock) {
System.out.println("t2启动..");
if(list2.size() != 5){
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前线程:" + Thread.currentThread().getName() + "收到通知线程停止..");
throw new RuntimeException();
}
}
}, "t2");
t2.start();
Thread.sleep(1000);
t1.start();
}
}
当list2.size==5时,唤醒t2线程,然后t1执行完后,t2拿到锁,可是此时list2.size已经是10了,为什么还是会执行下面的抛异常的代码呢?请各位大神指教一下,多谢