Java多线程系列--“基础篇”04之 synchronized关键字(六)
public void run() {
62 y.cSyncB();
63 }
64 }, "t32");
65
66
67 t31.start(); // 启动t31
68 t32.start(); // 启动t32
69 }
70
71 public static void main(String[] args) {
72 LockTest3 demo = new LockTest3();
73
74 demo.test3();
75 }
76 }
复制代码
运行结果:
复制代码
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t31 : cSyncA
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
t32 : cSyncB
复制代码
(04) 可以被同时访问。因为isSyncA()是实例方法,x.isSyncA()使用的是对象x的锁;而cSyncA()是静态方法,Something.cSyncA()可以理解对使用的是“类的锁”。因此,它们是可以被同时访问的。
复制代码
1 // LockTest4.java的源码
2 class Something {
3 public synchronized void isSyncA(){
4 try {
5 for (int i = 0; i < 5; i++) {
6 Thread.sleep(100); // 休眠100ms
7 System.out.println(Thread.currentThread().getName()+" : isSyncA");
8 }
9 }catch (InterruptedException ie) {
10 }
11 }
12 public synchronized void isSyncB(){
13 try {
14 for (int i = 0; i < 5; i++) {
15 Thread.sleep(100); // 休眠100ms
16 System.out.println(Thread.currentThread().getName()+" : isSyncB");
17 }
18 }catch (InterruptedException ie) {
19 }
20 }
21 public static synchronized void cSyncA(){
22 try {
23 for (int i = 0; i < 5; i++) {
24 Thread.sleep(100); // 休眠100ms
25 System.out.println(Thread.currentThread().getName()+" : cSyncA");
26 }
27 }catch (InterruptedException ie) {
28 }
29 }
30 public static synchronized void cSyncB(){
31 try {
32 for (int i = 0; i < 5; i++) {
33 Thread.sleep(100); // 休眠100ms
34 System.out.println(Thread.currentThread().getName()+" : cSyncB");
35 }
36 }catch (InterruptedException ie) {
37 }
38 }
39 }
40
41 public class LockTest4 {
42
43 Something x = new Something();
44 Something y = new Something();
45
46 // 比较(04) x.isSyncA()与Something.cSyncA()
47 private void test4() {
48 // 新建t41, t41会调用 x.isSyncA()
49 Thread t41 = new Thread(
50 new Runnable() {
51 @Override
52 public void run() {
53 x.isSyncA();
54 }
55 }, "t41");
56
57 // 新建t42, t42会调用 x.isSyncB()
58 Thread t42 = new Thread(
59 new Runnable() {
60 @Override
61 public void run() {
62 Something.cSyncA();
63 }
64 }, "t42");
65
66
67 t41.start(); // 启动t41
68 t42.start(); // 启动t42
69 }
70
71 public static void main(String[] args) {
72 LockTest4 demo = new LockTest4();
73
74 demo.test4();
75 }
76 }
复制代码
运行结果:
复制代码
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA
t41 : isSyncA
t42 : cSyncA