理解notify与wait在线程里面的使用

public class MultiThread {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub 8
  new Thread(new Thread1()).start();
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  new Thread(new Thread2()).start();  
 }
 
 
 private static class Thread1 implements Runnable
 {

  
  public void run() {
   // TODO Auto-generated method stub
//由于这里的Thread1和下面的Thread2内部run方法要用同一对象作为监视器,我们这里不能用this,因为在Thread2里面的this和这个Thread1的this不是同一个对象。我们用MultiThread.class这个字节码对象,当前虚拟机里引用这个变量时,指向的都是同一个对象。
   synchronized (MultiThread.class) {

    System.out.println("enter thread1...");
    
    System.out.println("thread1 is waiting");
    try {
   //释放锁有两种方式,第一种方式是程序自然离开监视器的范围,也就是离开了synchronized关键字管辖的代码范围,另一种方式就是在synchronized关键字管辖的代码内部调用监视器对象的wait方法。这里,使用wait方法释放锁。
     MultiThread.class.wait();
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    System.out.println("thread1 is going on...");
    System.out.println("thread1 is being over!");   
   }
  }
  
 }
 
 private static class Thread2 implements Runnable
 {

 
  public void run() {
   // TODO Auto-generated method stub
   synchronized (MultiThread.class) {
   
    System.out.println("enter thread2...");
    
    System.out.println("thread2 notify other thread can release wait status..");
//由于notify方法并不释放锁, 即使thread2调用下面的sleep方法休息了10毫秒,但thread1仍然不会执行,因为thread2没有释放锁,所以Thread1无法得不到锁。

    MultiThread.class.notify();
    
    System.out.println("thread2 is sleeping ten millisecond...");
    try {
     Thread.sleep(1000);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    System.out.println("thread2 is going on...");
    System.out.println("thread2 is being over!");
    
   }
  }
  
 } 

}

注解:wait()使进同步方法的线程战时让出锁 放在锁吃池里面,让其他线程去竞争。当其他线程调用notify()唤醒调用过wait()方法的线程,如果此时notify线程后面还有代码那么久先执行此线程后面的代码,然后执行以前调用过wait()方法的线程
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值