java多线程问题总结

来源:互联网 发布:少儿编程 网易 编辑:程序博客网 时间:2024/05/25 19:57
1、synchronized关键字修饰的同步函数使用什么对象作为锁?

分为两种情况,如果该函数为静态的则采用所在类的class锁,否则采用this锁,测试用例如下:

class test{public synchronized void f1() throws InterruptedException{  System.out.println("进入f1");Thread.sleep(5000);System.out.println("离开f1");}public void f2(){      synchronized (this){System.out.println("进入f2");      }}}public class thread{       public static void main(String[] args) throws InterruptedException {       test t=new test();          Thread t1=new Thread(new Runnable() {  @Override  public void run() {t.f1();  }    });       Thread t2=new Thread(new Runnable() { @Override public void run() {t.f2(); }   });              t1.start();       t2.start();   } }
输出结果:
进入f1
离开f1
进入f2
我们可以看到,只有当线程t1释放锁后,线程t2才能进入f2,说明同步方法和同步代码块采用的是同一个this锁,class锁的测试则给f1添加static关键字,f2使用test.class锁。


0 0
原创粉丝点击