import java.util.Random;
/**
* TODO 在此写上类的相关说明.<br>
* @author gongqiang <br>
* @version 1.0.0 2021年6月3日<br>
* @see
* @since JDK 1.5.0
*/
public class SynchronizedDemo {
/**
* 中间值.
*/
private Integer value;
/**
* @param args
*/
public static void main(String[] args) {
final SynchronizedDemo syn = new SynchronizedDemo();
new Thread(() -> {
while (true) {
try {
synchronized (SynchronizedDemo.class) {
final Integer value = new Random().nextInt();
syn.value = value;
System.out.println("设置共享" + value);
Thread.sleep(3000);
}
// 休眠,让获取线程能够读取共享变量.
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
new Thread(() -> {
while (true) {
synchronized (SynchronizedDemo.class) {
final Integer value = syn.value;
System.out.println("获取共享" + value);
}
// 休眠,让设置线程能够设置共享变量.
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
try {
Thread.sleep(60 * 60 * 1000);
} catch (InterruptedException e) {
// 无需处理.
}
}
}