update 78. 同步访问共享的可变数据

This commit is contained in:
sjsdfg 2019-03-15 11:23:16 +08:00
parent 4e9f050fa6
commit 9e165c8c41

View File

@ -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();
}
```