1. synchronized同步方法

1) synchronized修饰方法,表示方法是同步的,当某线程进入并拿到当前整个对象的锁时

a. 其他synchronized方法排队等锁

b. 非synchronized方法可异步执行

示例代码(折叠)

 1 package com.khlin.thread;
 2 
 3 public class SynchronizedTest {
 4     
 5     public static void main(String[] args) {
 6         Service service = new Service();
 7         /**
 8          * A B 两个方法是同步的,因此访问A时候,要等A方法执行完,A线程释放锁,B线程才能拿到锁从而访问B方法。
 9          * 而C方法并不是同步的,可以异步执行
10          */
11         ThreadA threadA = new ThreadA(service);
12         threadA.start();
13         
14         ThreadB threadB = new ThreadB(service);
15         threadB.start();
16         
17         ThreadC threadC = new ThreadC(service);
18         threadC.start();
19     }
20 }
21 
22 class ThreadA extends Thread {
23 
24     private Service service;
25 
26     public ThreadA(Service service) {
27         this.service = service;
28     }
29 
30     public void run() {
31         super.run();
32         service.printA();
33     }
34 }
35 
36 class ThreadB extends Thread {
37 
38     private Service service;
39 
40     public ThreadB(Service service) {
41         this.service = service;
42     }
43 
44     public void run() {
45         super.run();
46         service.printB();
47     }
48 }
49 
50 class ThreadC extends Thread {
51 
52     private Service service;
53 
54     public ThreadC(Service service) {
55         this.service = service;
56     }
57 
58     public void run() {
59         super.run();
60         service.printC();
61     }
62 }
63 
64 class Service {
65     public synchronized void printA() {
66 
67         System.out.println("enter printA. thread name: "
68                 + Thread.currentThread().getName());
69 
70         try {
71             Thread.sleep(3000L);
72         } catch (InterruptedException e) {
73             // TODO Auto-generated catch block
74             e.printStackTrace();
75         }
76 
77         System.out.println("leaving printA. thread name: "
78                 + Thread.currentThread().getName());
79     }
80 
81     public synchronized void printB() {
82 
83         System.out.println("enter printB. thread name: "
84                 + Thread.currentThread().getName());
85 
86         System.out.println("leaving printB. thread name: "
87                 + Thread.currentThread().getName());
88     }
89 
90     public void printC() {
91 
92         System.out.println("enter printC. thread name: "
93                 + Thread.currentThread().getName());
94 
95         System.out.println("leaving printC. thread name: "
96                 + Thread.currentThread().getName());
97     }
98 }
synchronized方法

相关文章:

猜你喜欢
  • 2021-05-04
  • 2021-10-10
  • 2022-01-10
  • 2021-07-08
相关资源
相似解决方案