首页 新闻 会员 周边

synchronized

0
悬赏园豆:5 [待解决问题]

public class MyThread extends Thread{
  private static int num;
  public void run() {
    for(int i=0;i<10;i++){
      synchronized (this.getClass()) {//使两个线程共享同一把锁
      num++;
      System.out.println("num="+num);
      if(num==5){
        try {
          this.getClass().wait();
        }catch (InterruptedException e) {
          e.printStackTrace();
        }

      }//if代码块结束

      this.getClass().notify();
    }//synchronized代码块结束
   }//for代码块结束
  }//run方法代码块
  public static void main(String[] args) {
    Thread t1 = new MyThread();
    Thread t2 = new MyThread();
    t1.start();
    t2.start();
  }
}

假如t1拿到锁后,执行到synchronized代码块结束,会再次回到for循环,继续执行(老师说的),但是它不是会把锁释放吗,这样t2也有机会进来了,整体就乱了。请教大神,是怎样的过程,synchronized代码块结束会不会释放锁

danfic的主页 danfic | 初学一级 | 园豆:197
提问于:2016-08-21 23:13
< >
分享
所有回答(1)
0

java不太熟,但按道理而言不会出现t1还在临界区内,t2也进来的情况。

而且这段代码中的锁可以用cas消除掉。

Daniel Cai | 园豆:10424 (专家六级) | 2016-08-23 10:17
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册