首页 > 代码库 > 深入同步语法

深入同步语法

1. 深入synchronized关键字

 1 class Service{
 2     public void fun1(){
 3         synchronized(this){
 4             try{
 5                 Thread.sleep(3000); //休眠3秒; 可能会异常
 6             }
 7             catch(Exception e){
 8                 System.out.println(e);
 9             }
               System.out.println("fun1");
10         }
11     }
12     public void fun2(){
13         synchronized(this){
14             System.out.println("fun2");
15         }
16     }
17 }
 1 class MyThread1 implements Runnable{{
 2     private Service service;
 3     
 4     public MyThread1(Service service){
 5         this.service = service;
 6     }
 7     
 8     public void run(){
 9         service.fun1();
10     }
11 }
 1 class MyThread2 implements Runnable{{
 2     private Service service;
 3     
 4     public MyThread2(Service service){
 5         this.service = service;
 6     }
 7     
 8     public void run(){
 9         service.fun2();
10     }
11 }
 1 class Test{
 2     public static void main(String args []){
 3         Service service = new Service();
//共用service对象
4 Thread t1 = new Thread(new MyThread1(service)); 5 Thread t2 = new Thread(new MyThread2(service)); 6 7 t1.start(); 8 t2.start(); 9 } 10 }

        t1.start(); ---> service.fun1(); ---> synchronized(this),其中this代表new Thread(new MyThread1(service));中传入的service---> 进入fun1就休眠, 则会执行

        fun2, fun2还是但同步锁还是锁住this,即service, service被线程fun1锁住在,

        

        一旦某一对象获得线程同步锁, 对象上所有被同步的代码统统不能执行