【多線程】Java併發中的鎖(草稿)

可重入鎖Synchronized

 1 public class DemoTest {
 2     public static void main(String[] args) {
 3         final DemoTest demoTest = new DemoTest();
 4 
 5         Thread thread1 = new Thread(new Runnable() {
 6             @Override
 7             public void run() {
 8                 System.out.println(Thread.currentThread().getName() + "run");
 9                 demoTest.method1();
10             }
11         });
12         thread1.setName("thread-1");
13         thread1.start();
14 
15         Thread thread2 = new Thread(new Runnable() {
16             @Override
17             public void run() {
18                 System.out.println(Thread.currentThread().getName() + "run");
19                 demoTest.method2();
20             }
21         });
22         thread2.setName("thread-2");
23         thread2.start();
24     }
25 
26     public synchronized void method1() {
27         System.out.println("method1 run in" + Thread.currentThread().getName());
28         try {
29             Thread.sleep(1000);
30             method2();
31         } catch (InterruptedException e) {
32             e.printStackTrace();
33         }
34     }
35 
36     public synchronized void method2() {
37         System.out.println("method2 run in" + Thread.currentThread().getName());
38     }
39 
40 }

運行結果

thread-1run
method1 run inthread-1
thread-2run
method2 run inthread-1
method2 run inthread-2

11

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章