wait和notify简单学习

学C的时间粗劣写过些wait和notify的代码,java里接触的时候并没有花什么时间学习,本质上来说并没有区别,这两个方法都要和锁配合使用,java里常见和synchronized关键词配合使用,使用上十分简单。需要注意的地方是wait会释放锁,而notify并不释放锁,仍然需要代码去释放锁,其他进程即使收到notify的信号,如果没有获得锁是无法唤醒的。
测试代码如下
public class DemoApplication {
//使用最简单的锁
public static Object lock=new Object();

public static class Thread1 extends Thread{
    @Override
    public void run() {
        synchronized (lock){
            System.out.println("this is "+Thread.currentThread().getId());
            try {
                //模拟工作1
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getId()+" begin to wait");
                lock.wait();
                System.out.println(Thread.currentThread().getId()+" get lock and restart");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+" work complete");
        }
    }
}
public static class Thread2 extends Thread{
    @Override
    public void run() {
        synchronized (lock){
            System.out.println("this is "+Thread.currentThread().getId());
            try {
                //模拟工作2
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+" egin to notify");
            lock.notify();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getId()+" work complete");
        }
    }
}

public static void main(String[] args) throws InterruptedException {
    new Thread1().start();
    new Thread2().start();

}

}

运行结果this is 1818 begin to waitthis is 1919 egin to notify19 work complete18 get lock and restart18 work complete

公众号推荐
   一个健康类的公众号,欢迎关注
小青桔健康