java多线程—wait,notify,notifyAll关键字
wait,notify和notifyAll主要用于线程之间的通信。任何实例调用wait()后都会变为非活动状态,直到另一个线程在该实例上调用notify()。代码如下:
public class ThreadTest {
public static void main(String[] args){
ThreadWait thread = new ThreadWait();
thread.start();
synchronized(thread){
try{
System.out.println("等待线程thread执行完毕");
thread.wait();
System.out.println("线程thread执行结果: " + thread.total);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
class ThreadWait extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}
在上面的main函数中,当调用thread.wait()后,main函数主线程将出于非活跃状态,在线程thread执行norify()时,再将其唤醒, 我们可以看到执行的结果是:
等待线程B执行完毕
线程B执行结果: 4950
如果我们不使用wait()和notify(),代码如下:
public class ThreadTest {
public static void main(String[] args){
ThreadWait thread = new ThreadWait();
thread.start();
System.out.println("线程B执行结果: " + thread.total);
}
}
class ThreadWait extends Thread{
int total;
@Override
public void run(){
for(int i=0; i<100 ; i++){
total += i;
}
}
}
这里main函数的主线程没有出于阻塞状态,所以不管thread是否执行完毕,主线程都会继续执行下面,其运行结果如下:
线程B执行结果: 0