synchronized常见用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012279452/article/details/82017397

一 修饰方法

Synchronized修饰一个方法很简单,就是在方法的前面加synchronized,synchronized修饰方法和修饰一个代码块类似,只是作用范围不一样,修饰代码块是大括号括起来的范围,而修饰方法范围是整个函数。

Ex:

一、

  1. public synchronized void method()
  2. {
  3. // todo
  4. }

二、

  1. public void method()
  2. {
  3.    synchronized(this) {
  4.       // todo
  5.    }
  6. }

写法一修饰的是一个方法,写法二修饰的是一个代码块,但写法一与写法二是等价的,都是锁定了整个方法时的内容。

synchronized关键字不能继承。 
虽然可以使用synchronized来定义方法,但synchronized并不属于方法定义的一部分,因此,synchronized关键字不能被继承。如果在父类中的某个方法使用了synchronized关键字,而在子类中覆盖了这个方法,在子类中的这个方法默认情况下并不是同步的,而必须显式地在子类的这个方法中加上synchronized关键字才可以。当然,还可以在子类方法中调用父类中相应的方法,这样虽然子类中的方法不是同步的,但子类调用了父类的同步方法,因此,子类的方法也就相当于同步了。这两种方式的例子代码如下: 
在子类方法中加上synchronized关键字

  1. class Parent {
  2. public synchronized void method() { }
  3. }
  4. class Child extends Parent {
  5. public synchronized void method() { }
  6. }

在子类方法中调用父类的同步方法

  1. class Parent {
  2.    public synchronized void method() {   }
  3. }
  4. class Child extends Parent {
  5.    public void method() { super.method();   }
  6. 在定义接口方法时不能使用synchronized关键字。
  7. 构造方法不能使用synchronized关键字,但可以使用synchronized代码块来进行同步。 

 二 修饰一个代码块

1)一个线程访问一个对象中的synchronized(this)同步代码块时,其他试图访问该对象的线程将被阻塞

注意下面两个程序的区别

扫描二维码关注公众号,回复: 4075043 查看本文章
  1. class SyncThread implements Runnable {
  2.        private static int count;
  3.  
  4.        public SyncThread() {
  5.           count = 0;
  6.        }
  7.  
  8.        public  void run() {
  9.           synchronized(this) {
  10.              for (int i = 0; i < 5; i++) {
  11.                 try {
  12.                    System.out.println(Thread.currentThread().getName() + ":" + (count++));
  13.                    Thread.sleep(100);
  14.                 } catch (InterruptedException e) {
  15.                    e.printStackTrace();
  16.                 }
  17.              }
  18.           }
  19.        }
  20.  
  21.        public int getCount() {
  22.           return count;
  23.        }
  24. }
  25.  
  26. public class Demo00 {
  27.     public static void main(String args[]){
  28. //test01
  29. //        SyncThread s1 = new SyncThread();
  30. //        SyncThread s2 = new SyncThread();
  31. //        Thread t1 = new Thread(s1);
  32. //        Thread t2 = new Thread(s2);
  33. //test02        
  34.         SyncThread s = new SyncThread();
  35.         Thread t1 = new Thread(s);
  36.         Thread t2 = new Thread(s);
  37.         
  38.         t1.start();
  39.         t2.start();
  40.     }
  41. }

test1运行结果:

test2运行结果:

当两个并发线程(thread1和thread2)访问同一个对象(syncThread)中的synchronized代码块时,在同一时刻只能有一个线程得到执行,另一个线程受阻塞,必须等待当前线程执行完这个代码块以后才能执行该代码块。Thread1和thread2是互斥的,因为在执行synchronized代码块时会锁定当前的对象,只有执行完该代码块才能释放该对象锁,下一个线程才能执行并锁定该对象

为什么上面的例子中thread1和thread2同时在执行。这是因为synchronized只锁定对象,每个对象只有一个锁(lock)与之相关联。

2)当一个线程访问对象的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该对象中的非synchronized(this)同步代码块

ex:

  1.  class Counter implements Runnable{
  2.    private int count;
  3.  
  4.    public Counter() {
  5.       count = 0;
  6.    }
  7.  
  8.    public void countAdd() {
  9.       synchronized(this) {
  10.          for (int i = 0; i < 5; i ++) {
  11.             try {
  12.                System.out.println(Thread.currentThread().getName() + ":" + (count++));
  13.                Thread.sleep(100);
  14.             } catch (InterruptedException e) {
  15.                e.printStackTrace();
  16.             }
  17.          }
  18.       }
  19.    }
  20.  
  21.    //非synchronized代码块,未对count进行读写操作,所以可以不用synchronized
  22.    public void printCount() {
  23.       for (int i = 0; i < 5; i ++) {
  24.          try {
  25.             System.out.println(Thread.currentThread().getName() + " count:" + count);
  26.             Thread.sleep(100);
  27.          } catch (InterruptedException e) {
  28.             e.printStackTrace();
  29.          }
  30.       }
  31.    }
  32.  
  33.    public void run() {
  34.       String threadName = Thread.currentThread().getName();
  35.       if (threadName.equals("A")) {
  36.          countAdd();
  37.       } else if (threadName.equals("B")) {
  38.          printCount();
  39.       }
  40.    }
  41. }
  42.  
  43. public class Demo00{
  44.     public static void main(String args[]){
  45.         Counter counter = new Counter();
  46.         Thread thread1 = new Thread(counter, "A");
  47.         Thread thread2 = new Thread(counter, "B");
  48.         thread1.start();
  49.         thread2.start();
  50.     }
  51. }

结果:

B count:0
A:0
B count:1
A:1
B count:2
A:2
B count:4
A:3
A:4
B count:5

可以看见B线程的调用是非synchronized,并不影响A线程对synchronized部分的调用。从上面的结果中可以看出一个线程访问一个对象的synchronized代码块时,别的线程可以访问该对象的非synchronized代码块而不受阻塞。

3)指定要给某个对象加锁

  1. /**
  2.  * 银行账户类
  3.  */
  4. class Account {
  5.    String name;
  6.    float amount;
  7.  
  8.    public Account(String name, float amount) {
  9.       this.name = name;
  10.       this.amount = amount;
  11.    }
  12.    //存钱
  13.    public  void deposit(float amt) {
  14.       amount += amt;
  15.       try {
  16.          Thread.sleep(100);
  17.       } catch (InterruptedException e) {
  18.          e.printStackTrace();
  19.       }
  20.    }
  21.    //取钱
  22.    public  void withdraw(float amt) {
  23.       amount -= amt;
  24.       try {
  25.          Thread.sleep(100);
  26.       } catch (InterruptedException e) {
  27.          e.printStackTrace();
  28.       }
  29.    }
  30.  
  31.    public float getBalance() {
  32.       return amount;
  33.    }
  34. }
  35.  
  36. /**
  37.  * 账户操作类
  38.  */
  39. class AccountOperator implements Runnable{
  40.    private Account account;
  41.    public AccountOperator(Account account) {
  42.       this.account = account;
  43.    }
  44.  
  45.    public void run() {
  46.       synchronized (account) {
  47.          account.deposit(500);
  48.          account.withdraw(500);
  49.          System.out.println(Thread.currentThread().getName() + ":" + account.getBalance());
  50.       }
  51.    }
  52. }
  53.  
  54. public class Demo00{
  55.     
  56.     //public static final Object signal = new Object(); // 线程间通信变量
  57.     //将account改为Demo00.signal也能实现线程同步
  58.     public static void main(String args[]){
  59.         Account account = new Account("zhang san", 10000.0f);
  60.         AccountOperator accountOperator = new AccountOperator(account);
  61.  
  62.         final int THREAD_NUM = 5;
  63.         Thread threads[] = new Thread[THREAD_NUM];
  64.         for (int i = 0; i < THREAD_NUM; i ++) {
  65.            threads[i] = new Thread(accountOperator, "Thread" + i);
  66.            threads[i].start();
  67.         }
  68.     }

结果:

Thread0:10000.0
Thread4:10000.0
Thread3:10000.0
Thread2:10000.0
Thread1:10000.0

在AccountOperator 类中的run方法里,我们用synchronized 给account对象加了锁。这时,当一个线程访问account对象时,其他试图访问account对象的线程将会阻塞,直到该线程访问account对象结束。也就是说谁拿到那个锁谁就可以运行它所控制的那段代码。 
当有一个明确的对象作为锁时,就可以用类似下面这样的方式写程序。

public void method3(SomeObject obj)
{
   //obj 锁定的对象
   synchronized(obj)
   {
      // todo
   }
}

当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的对象来充当锁:

  1. class Test implements Runnable
  2. {
  3.    private byte[] lock = new byte[0];  // 特殊的instance变量
  4.    public void method()
  5.    {
  6.       synchronized(lock) {
  7.          // todo 同步代码块
  8.       }
  9.    }
  10.  
  11.    public void run() {
  12.  
  13.    }
  14. }

三 修饰一个静态的方法

Synchronized也可修饰一个静态方法,用法如下: 

  1. public synchronized static void method() {
  2.    // todo
  3. }
  4. 静态方法是属于类的而不属于对象的。同样的,synchronized修饰的静态方法锁定的是这个类的所有对象。
  5.  /**
  6.  * 同步线程
  7.  */
  8. class SyncThread implements Runnable {
  9.    private static int count;
  10.  
  11.    public SyncThread() {
  12.       count = 0;
  13.    }
  14.  
  15.    public synchronized static void method() {
  16.       for (int i = 0; i < 5; i ++) {
  17.          try {
  18.             System.out.println(Thread.currentThread().getName() + ":" + (count++));
  19.             Thread.sleep(100);
  20.          } catch (InterruptedException e) {
  21.             e.printStackTrace();
  22.          }
  23.       }
  24.    }
  25.  
  26.    public synchronized void run() {
  27.       method();
  28.    }
  29. }
  30.  
  31. public class Demo00{
  32.     
  33.     public static void main(String args[]){
  34.         SyncThread syncThread1 = new SyncThread();
  35.         SyncThread syncThread2 = new SyncThread();
  36.         Thread thread1 = new Thread(syncThread1, "SyncThread1");
  37.         Thread thread2 = new Thread(syncThread2, "SyncThread2");
  38.         thread1.start();
  39.         thread2.start();
  40.     }
  41. }

结果:

SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9

syncThread1和syncThread2是SyncThread的两个对象,但在thread1和thread2并发执行时却保持了线程同步。这是因为run中调用了静态方法method,而静态方法是属于类的,所以syncThread1和syncThread2相当于用了同一把锁。

四  修饰一个类

本例的的给class加锁和上例的给静态方法加锁是一样的,所有对象公用一把锁

Synchronized还可作用于一个类,用法如下: 

  1. class ClassName {
  2.    public void method() {
  3.       synchronized(ClassName.class) {
  4.          // todo
  5.       }
  6.    }
  7. /**
  8.  * 同步线程
  9.  */
  10. class SyncThread implements Runnable {
  11.    private static int count;
  12.  
  13.    public SyncThread() {
  14.       count = 0;
  15.    }
  16.  
  17.    public static void method() {
  18.       synchronized(SyncThread.class) {
  19.          for (int i = 0; i < 5; i ++) {
  20.             try {
  21.                System.out.println(Thread.currentThread().getName() + ":" + (count++));
  22.                Thread.sleep(100);
  23.             } catch (InterruptedException e) {
  24.                e.printStackTrace();
  25.             }
  26.          }
  27.       }
  28.    }
  29.  
  30.    public synchronized void run() {
  31.       method();
  32.    }
  33. }

总结

A. 无论synchronized关键字加在方法上还是对象上,如果它作用的对象是非静态的,则它取得的锁是对象;如果synchronized作用的对象是一个静态方法或一个类,则它取得的锁是对类,该类所有的对象同一把锁。 
B. 每个对象只有一个锁(lock)与之相关联,谁拿到这个锁谁就可以运行它所控制的那段代码。 
C. 实现同步是要很大的系统开销作为代价的,甚至可能造成死锁,所以尽量避免无谓的同步控制。

猜你喜欢

转载自blog.csdn.net/u012279452/article/details/82017397