diff --git a/docs/notes/78. 同步访问共享的可变数据.md b/docs/notes/78. 同步访问共享的可变数据.md index 25a965e..5bab635 100644 --- a/docs/notes/78. 同步访问共享的可变数据.md +++ b/docs/notes/78. 同步访问共享的可变数据.md @@ -15,14 +15,13 @@ public class StopThread { private static Boolean stopRequested; - public static void main(String[] args) - throws InterruptedException { + public static void main(String[] args) + throws InterruptedException { Thread backgroundThread = new Thread(() -> { int i = 0; while (!stopRequested) i++; - } - ); + }); backgroundThread.start(); TimeUnit.SECONDS.sleep(1); stopRequested = true; @@ -39,7 +38,7 @@ while (!stopRequested) i++; ``` -转变成这样: +  转变成这样: ```java if (!stopRequested) @@ -54,25 +53,24 @@ if (!stopRequested) ```java // Properly synchronized cooperative thread termination public class StopThread { - private static Boolean stopRequested; - private static synchronized void requestStop() { - stopRequested = true; - } - private static synchronized Boolean stopRequested() { - return stopRequested; - } - public static void main(String[] args) - throws InterruptedException { - Thread backgroundThread = new Thread(() -> { - int i = 0; - while (!stopRequested()) - i++; - } - ); - backgroundThread.start(); - TimeUnit.SECONDS.sleep(1); - requestStop(); - } + private static Boolean stopRequested; + private static synchronized void requestStop() { + stopRequested = true; + } + private static synchronized Boolean stopRequested() { + return stopRequested; + } + public static void main(String[] args) + throws InterruptedException { + Thread backgroundThread = new Thread(() -> { + int i = 0; + while (!stopRequested()) + i++; + }); + backgroundThread.start(); + TimeUnit.SECONDS.sleep(1); + requestStop(); + } } ``` @@ -83,19 +81,18 @@ public class StopThread { ```java // Cooperative thread termination with a volatile field public class StopThread { - private static volatile Boolean stopRequested; - public static void main(String[] args) - throws InterruptedException { - Thread backgroundThread = new Thread(() -> { - int i = 0; - while (!stopRequested) - i++; - } - ); - backgroundThread.start(); - TimeUnit.SECONDS.sleep(1); - stopRequested = true; - } + private static volatile Boolean stopRequested; + public static void main(String[] args) + throws InterruptedException { + Thread backgroundThread = new Thread(() -> { + int i = 0; + while (!stopRequested) + i++; + }); + backgroundThread.start(); + TimeUnit.SECONDS.sleep(1); + stopRequested = true; + } } ``` @@ -106,7 +103,7 @@ public class StopThread { private static volatile int nextSerialNumber = 0; public static int generateSerialNumber() { - return nextSerialNumber++; + return nextSerialNumber++; } ``` @@ -123,7 +120,7 @@ public static int generateSerialNumber() { private static final Atomiclong nextSerialNum = new Atomiclong(); public static long generateSerialNumber() { - return nextSerialNum.getAndIncrement(); + return nextSerialNum.getAndIncrement(); } ```