【多线程】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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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