9.线程通信wait、notify
线程之间通信
1.线程是操作系统的独立的个体,但这些个体如果不经过特殊处理就不能成为一个整体。
2.使用wait、notify,方法实现线程通信(2个方法都是需要object方法)
3.wait(释放锁)、notify(不会释放锁)必须配合synchronized关键字使用。
package demo2;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liudan on 2017/7/4.
*/
public class MyThread2_2 {
private volatile static List<String> lsit = new ArrayList<String>();
public void add() {
lsit.add("add......");
}
public int size() {
return lsit.size();
}
public static void main(String[] args) {
final MyThread2_1 myThread2_1 = new MyThread2_1();
final Object o = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o) {
try {
for (int i = 0; i < 10; i++) {
myThread2_1.add();
System.err.println("当前线程:" + Thread.currentThread().getName() + "添加了一个元素");
Thread.sleep(500);
if (myThread2_1.size() == 5) {
System.err.println("发起通知");
o.notify();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (o) {
if (myThread2_1.size()!= 5) {
System.err.println("t2 进入");
try {
o.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.err.println("当前线程:" + Thread.currentThread().getName() + "收到通知...");
}
}
}, "t2");
t2.start();
t1.start();
}
}