From 30db149f1a55f9643d781cc98cb5fcaebbafe026 Mon Sep 17 00:00:00 2001 From: whaifree <49432110+whaibetter@users.noreply.github.com> Date: Fri, 16 Aug 2024 00:35:26 +0800 Subject: [PATCH] =?UTF-8?q?```=E6=B7=BB=E5=8A=A0=E6=BC=94=E7=A4=BA?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=96=B9=E6=B3=95=E7=9A=84=E7=94=A8=E6=B3=95?= =?UTF-8?q?=E4=BB=A5=E9=98=B2=E6=AD=A2=E5=AE=9E=E4=BE=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增的syn类演示了同步方法的用法,以防止在多线程环境中实例化。这通过尝试获取对象锁并打印对象引用的getLock方法以及调用wait的printSyn方法进行演示。 ``` --- .../redo/redo_all_240721/LeetCode343.java | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode343.java b/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode343.java index b175bd8..d067ddb 100644 --- a/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode343.java +++ b/src/main/java/cn/whaifree/redo/redo_all_240721/LeetCode343.java @@ -45,7 +45,46 @@ public class LeetCode343 { static Object o = new Object(); static int count = 0; + static class syn{ + public static void main(String[] args) throws InterruptedException { + syn syn = new syn(); + // 创建一个线程来调用 printSyn 方法 + Thread thread1 = new Thread(() -> { + try { + syn.printSyn(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + }); + // 创建另一个线程来调用 getLock 方法 + Thread thread2 = new Thread(() -> { + syn.getLock(); + }); + thread1.start(); + thread2.start(); + } + + public synchronized void printSyn() throws InterruptedException { + Thread.sleep(1000); // 睡眠,看this是不是被其他线程拿走了 + // 睡眠的过程中拿着this,下面的this不能拿到 + this.wait(); // 卡在这 + System.out.println("syn"); + } + + // 另一个线程尝试去获取this对象 + public synchronized void getLock() { + System.out.println(this); + } + } + public static void main(String[] args) { + int a = 100; + long b = 100L; + System.out.println(a==b); + + float c = 1.0f; + int d = 1; + System.out.println(c==d); new Thread(() -> { for (int i = 0; i < 100; i++) {