码迷,mamicode.com
首页 > 其他好文 > 详细

深入同步语法

时间:2014-05-23 03:28:22      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

1. 深入synchronized关键字

bubuko.com,布布扣
 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 }
bubuko.com,布布扣
bubuko.com,布布扣
 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 }
bubuko.com,布布扣
bubuko.com,布布扣
 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 }
bubuko.com,布布扣
bubuko.com,布布扣
 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 }
bubuko.com,布布扣

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

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

         bubuko.com,布布扣

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

 

深入同步语法,布布扣,bubuko.com

深入同步语法

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/iMirror/p/3742650.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!