Java并发编程入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

等待和通知

为了支持多线程之间的合作,JDK提供了两个非常重要的接口:线程等待(wait())和通知(notify()),这两个方法的签名如下:

public final void wait() throws InterruptedException
public final native void notify()

这两个方法是final修饰的,不能被重写,而且notify是本地方法。当一个对象的实例调用了wait之后,当前线程就会在这个对象上等待,直到其他线程中有调用了notify方法的时候。Object中也有类似的方法,但是不能随便调用的。下面给大家一个实例说明这两个方法的用法。

public class Main {
    final static Object object=new Object();
    public static class T1 extends Thread{
        public void run(){
            synchronized (object){
                System.out.println(System.currentTimeMillis()+"T1 start");
                try {
                    System.out.println(System.currentTimeMillis()+"T1 waite");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(System.currentTimeMillis()+"T1 end");
            }
        }
    }
    public static class T2 extends Thread{
        public void run(){
            synchronized (object){
                System.out.println(System.currentTimeMillis()+"T2 start");
                object.notify();
                System.out.println(System.currentTimeMillis()+"T2 end");
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void main(String[] args){
        Thread thread1=new T1();
        Thread thread2=new T2();
        thread1.start();
        thread2.start();
    }
}
试着写两个线程,一个等待一个通知,了解具体执行过程,如果自己写不出来,可以尝试运行以上代码,观察运行。