Java synchronized

Java的关键字,当用它修饰一个方法或者代码块时候,能够保证同一时刻最多只有一个线程执行该段代码

1.当一个线程访问object的一个synchronized(this)同步代码块时,其他线程对object中所有的synchronized(this)同步代码块访问都阻塞。因为访问线程获得了这个object的对象锁。

2.一个线程访问objec的一个synchronized(this)同步代码块时,另一个线程可以访问该object的非synchronized(this)同步代码块。


用法
1.修饰方法
public synchronized void accessVal(int newVal);
缺点:把一个大的方法声明为synchronized会极大影响效率。如果把线程类的run()声明为synchronized,由于线程的整个生命周期内它一直运行,因此将导致任何对本类synchronized方法调用永远阻塞。


2.修饰代码块

synchronized(syncObject) {
     // 同步代码块
}
执行同步代码块前必须获得对象syncObject(类或对象)的锁方能执行,可以针对任意代码块,指定锁上任意对象,灵活性高。
public class Thread2 {
     public void m4t1() {
          synchronized(this) {
               int i = 5;
               while( i-- > 0) {
                    System.out.println(Thread.currentThread().getName() + " : " + i);
                    try {
                         Thread.sleep(500);
                    } catch (InterruptedException ie) {
                    }
               }
          }
     }
     public void m4t2() {
          int i = 5;
          while( i-- > 0) {
               System.out.println(Thread.currentThread().getName() + " : " + i);
               try {
                    Thread.sleep(500);
               } catch (InterruptedException ie) {
               }
          }
     }
     public static void main(String[] args) {
          final Thread2 myt2 = new Thread2();
          Thread t1 = new Thread(  new Runnable() {  public void run() {  myt2.m4t1();  }  }, "t1"  );
          Thread t2 = new Thread(  new Runnable() {  public void run() { myt2.m4t2();   }  }, "t2"  );
          t1.start();
          t2.start();
     }
}

结果:
     t1 : 4
     t2 : 4
     t1 : 3
     t2 : 3
     t1 : 2
     t2 : 2
     t1 : 1
     t2 : 1
     t1 : 0
     t2 : 0

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值