【多线程】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

 

posted @   宋者为王  阅读(164)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2019-07-19 【朝花夕拾】Android自定义View篇之(十一)View的滑动,弹性滑动与自定义PagerView
点击右上角即可分享
微信分享提示