线程Blocked--SynchronizedDemo
生活随笔
收集整理的这篇文章主要介绍了
线程Blocked--SynchronizedDemo
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
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) {// 无需处理.}}
}
总结
以上是生活随笔为你收集整理的线程Blocked--SynchronizedDemo的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: Java并发编程实战~Guarded S
- 下一篇: 生产者-消费者 BlockingQueu