线程Blocked--SynchronizedDemo
生活随笔
收集整理的這篇文章主要介紹了
线程Blocked--SynchronizedDemo
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
import java.util.Random;/*** TODO 在此寫(xiě)上類(lèi)的相關(guān)說(shuō)明.<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("設(shè)置共享" + value);Thread.sleep(3000);}// 休眠,讓獲取線(xiàn)程能夠讀取共享變量.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);}// 休眠,讓設(shè)置線(xiàn)程能夠設(shè)置共享變量.try {Thread.sleep(500);} catch (InterruptedException e) {Thread.currentThread().interrupt();}}}).start();try {Thread.sleep(60 * 60 * 1000);} catch (InterruptedException e) {// 無(wú)需處理.}}
}
?
總結(jié)
以上是生活随笔為你收集整理的线程Blocked--SynchronizedDemo的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Java并发编程实战~Guarded S
- 下一篇: 生产者-消费者 BlockingQueu