synchronized的四种用法

https://blog.csdn.net/sinat_32588261/article/details/72880159

一 修饰方法

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

例如:

方法一

 
  1. public synchronized void method()

  2. {

  3. // todo

    扫描二维码关注公众号,回复: 2810786 查看本文章
  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. }

  1. 在定义接口方法时不能使用synchronized关键字。
  2. 构造方法不能使用synchronized关键字,但可以使用synchronized代码块来进行同步。 


 

二 修饰一个代码块

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

注意下面两个程序的区别

 
  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. }


test01的运行结果

test02的运行结果

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

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

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

例:

 
  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线程的调用是非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. }

  69. }


运行结果

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

 
  1. public void method3(SomeObject obj)

  2. {

  3. //obj 锁定的对象

  4. synchronized(obj)

  5. {

  6. // todo

  7. }

  8. }


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

 
  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. }

本例中去掉注释中的signal可以看到同样的运行结果


三 修饰一个静态的方法

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

 
  1. public synchronized static void method() {

  2. // todo

  3. }


静态方法是属于类的而不属于对象的。同样的,synchronized修饰的静态方法锁定的是这个类的所有对象。

 
  1. /**

  2. * 同步线程

  3. */

  4. class SyncThread implements Runnable {

  5. private static int count;

  6.  
  7. public SyncThread() {

  8. count = 0;

  9. }

  10.  
  11. public synchronized static void method() {

  12. for (int i = 0; i < 5; i ++) {

  13. try {

  14. System.out.println(Thread.currentThread().getName() + ":" + (count++));

  15. Thread.sleep(100);

  16. } catch (InterruptedException e) {

  17. e.printStackTrace();

  18. }

  19. }

  20. }

  21.  
  22. public synchronized void run() {

  23. method();

  24. }

  25. }

  26.  
  27. public class Demo00{

  28.  
  29. public static void main(String args[]){

  30. SyncThread syncThread1 = new SyncThread();

  31. SyncThread syncThread2 = new SyncThread();

  32. Thread thread1 = new Thread(syncThread1, "SyncThread1");

  33. Thread thread2 = new Thread(syncThread2, "SyncThread2");

  34. thread1.start();

  35. thread2.start();

  36. }

  37. }


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

四  修饰一个类

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

 
  1. class ClassName {

  2. public void method() {

  3. synchronized(ClassName.class) {

  4. // todo

  5. }

  6. }

  7. }

 
  1. /**

  2. * 同步线程

  3. */

  4. class SyncThread implements Runnable {

  5. private static int count;

  6.  
  7. public SyncThread() {

  8. count = 0;

  9. }

  10.  
  11. public static void method() {

  12. synchronized(SyncThread.class) {

  13. for (int i = 0; i < 5; i ++) {

  14. try {

  15. System.out.println(Thread.currentThread().getName() + ":" + (count++));

  16. Thread.sleep(100);

  17. } catch (InterruptedException e) {

  18. e.printStackTrace();

  19. }

  20. }

  21. }

  22. }

  23.  
  24. public synchronized void run() {

  25. method();

  26. }

  27. }

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

总结

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

猜你喜欢

转载自blog.csdn.net/m0_38054145/article/details/81605321
今日推荐