本文主要给出的是synchronized在不同场景中的不同用法的代码段,可直接编译后运行,不理解的人可以在学习synchronized关键字后再运行此代码,会有顿悟般的感觉哦
1 /**
2 * method1与method2是为了解决不同线程对一个类的同一个对象的操作
3 * method3与method4是为了解决不同线程对同一个类不同对象的操作
4 * @author Liang
5 * @since 2019-08-06 17:54
6 */
7 public class SynchronizedMethodDemo implements Runnable {
8
9 static SynchronizedMethodDemo synchronizedMethodDemo0 = new SynchronizedMethodDemo();
10 static SynchronizedMethodDemo synchronizedMethodDemo1 = new SynchronizedMethodDemo();
11
12 @Override
13 public void run() {
14 // method1();
15 // method2();
16 // method3();
17 method4();
18 }
19
20 /**
21 * method1与method2是同一段代码的两种不同写法
22 * 方法中synchronized默认所指的对象是this
23 */
24 private synchronized void method1() {
25 System.out.println("我是线程"+Thread.currentThread().getName());
26 try {
27 Thread.sleep(2000);
28 } catch (InterruptedException e) {
29 e.printStackTrace();
30 }
31 }
32
33 private void method2() {
34 synchronized (this){
35 System.out.println("我是线程"+Thread.currentThread().getName());
36 try {
37 Thread.sleep(2000);
38 } catch (InterruptedException e) {
39 e.printStackTrace();
40 }
41 }
42 }
43
44 /**
45 * 对不同线程访问同一个类不同对象时的两种方式
46 * 1. synchronized (*.class)代码段
47 * 2. static synchronized 方法
48 */
49 private void method3() {
50 synchronized (SynchronizedMethodDemo.class){
51 System.out.println("我是线程"+Thread.currentThread().getName());
52 try {
53 Thread.sleep(2000);
54 } catch (InterruptedException e) {
55 e.printStackTrace();
56 }
57 }
58 }
59
60 private static synchronized void method4() {
61 System.out.println("我是线程"+Thread.currentThread().getName());
62 try {
63 Thread.sleep(2000);
64 } catch (InterruptedException e) {
65 e.printStackTrace();
66 }
67 }
68
69 public static void main(String[] args) {
70 // 注释掉的部分是多线程对同一对象的操作
71 // Thread thread0 = new Thread(synchronizedMethodDemo0);
72 // Thread thread1 = new Thread(synchronizedMethodDemo0);
73 Thread thread0 = new Thread(synchronizedMethodDemo0);
74 Thread thread1 = new Thread(synchronizedMethodDemo1);
75
76 thread0.start();
77 thread1.start();
78
79 }
80 }