1.不适用等待/通知机制实现线程通信
import java.util.ArrayList;
import java.util.List;
class MyList{
private List list = new ArrayList();
public void add(){
list.add("123");
}
public int size(){
return list.size();
}
}
class ThreadA implements Runnable{
private MyList list;
public ThreadA(MyList list){
this.list = list;
}
public void run(){
try{
for(int i = 0;i < 10;++i){
list.add();
System.out.println("添加了"+(i+1)+"个元素");
Thread.sleep(1000);
}
}catch(InterruptedException e){
}
}
}
class ThreadB implements Runnable{
private MyList list;
public ThreadB(MyList list){
this.list = list;
}
public void run(){
try{
while(true){
System.out.println("b");
if(list.size() == 5){
System.out.println("==5,线程b要退出了");
throw new InterruptedException();
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class Test {
public static void main(String[] args){
MyList service = new MyList();
ThreadA a = new ThreadA(service);
new Thread(a).start();
ThreadB b = new ThreadB(service);
new Thread(b).start();
}
}
这个有一定的不确定性,我们并不知道B线程是否已经运行了,而且通过while(true)轮询来检测条件,浪费CPU资源
2.等待通知机制。wait()使当前执行代码的线程进行等待,notify()通知一个等待线程准备运行,但并不是立即执行。另外wait()和notify()需要在同步方法或同步块中调用
import java.util.ArrayList;
import java.util.List;
class MyList01{
private static List list = new ArrayList();
public static void add(){
list.add("123");
}
public static int size(){
return list.size();
}
}
class ThreadA implements Runnable{
private Object lock;
public ThreadA(Object lock){
this.lock = lock;
}
public void run(){
try{
synchronized (lock) {
if (MyList01.size() != 5) {
System.out.println("wait begin" + System.currentTimeMillis());
lock.wait();
System.out.println("wait end" + System.currentTimeMillis());
}
}
}catch(InterruptedException e){
}
}
}
class ThreadB implements Runnable{
private Object lock;
public ThreadB(Object lock){
this.lock = lock;
}
public void run(){
try{
synchronized (lock){
for(int i = 0;i < 10;++i){
MyList01.add();
if(MyList01.size() == 5){
lock.notify();
System.out.println("已发出通知");
}
System.out.println("添加了"+(i+1)+"个元素");
Thread.sleep(1000);
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class Run {
public static void main(String[] args){
Object lock = new Object();
ThreadA a = new ThreadA(lock);
new Thread(a).start();
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
ThreadB b = new ThreadB(lock);
new Thread(b).start();
}
}
日志信息wait end在最后输出,说明notify()执行后,并不会立即释放锁