From d4b24c30d4654b6fc5e6eefc8dc4fd0d2ed73a95 Mon Sep 17 00:00:00 2001 From: pj3q7x5mz <1732875197@qq.com> Date: Thu, 17 Nov 2022 11:21:49 +0800 Subject: [PATCH] ADD file via upload --- ... - 多线程基础(3)线程同步.txt | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Java高级特性 - 多线程基础(3)线程同步.txt diff --git a/Java高级特性 - 多线程基础(3)线程同步.txt b/Java高级特性 - 多线程基础(3)线程同步.txt new file mode 100644 index 0000000..822cbad --- /dev/null +++ b/Java高级特性 - 多线程基础(3)线程同步.txt @@ -0,0 +1,36 @@ +1.使用synchronized关键字同步线程 +package step2; + +public class Task { + + public static void main(String[] args) { + + final insertData insert = new insertData(); + + for (int i = 0; i < 3; i++) { + new Thread(new Runnable() { + public void run() { + insert.insert(Thread.currentThread()); + } + }).start(); + } + + } +} + +class insertData { + + public static int num = 0; + + /********* Begin *********/ + public synchronized void insert(Thread thread) { + + for (int i = 0; i <= 5; i++) { + num++; + System.out.println(num); + } + } + + /********* End *********/ +} +