【Java】多线程之线程可见性synchronized

synchronized的规定

  • 线程解锁前,必须把共享变量刷新到主内存
  • 线程加锁前将清空工作内存共享变量的值,需要从主存中获取共享变量的值。

【Java】多线程之线程可见性synchronized

synchronized线程可见性安全案例

package com.keytech.task;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class SynchronizedTestOne {

public static void main(String[] args) {

ExecutorService executorService = Executors.newCachedThreadPool();

Rumenzz r=new Rumenzz();

//线程1

executorService.execute(()->{

r.setAge(200);

});

//线程2

executorService.execute(()->{

System.out.println(r.getAge());

});

executorService.shutdown();

}

}

class Rumenzz{

private Integer age=0;

public synchronized Integer getAge() {

return age;

}

public synchronized void setAge(Integer age) {

this.age = age;

}

}

package com.keytech.task;

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

/**

* @className: SynchronizedTestOne

* @description: TODO 类描述

* @author: mac

* @date: 2021/1/1

**/

public class SynchronizedTestOne {

public static void main(String[] args) {

ExecutorService executorService = Executors.newCachedThreadPool();

Rumenzz r=new Rumenzz();

CountDownLatch c=new CountDownLatch(1);

executorService.execute(()->{

try {

c.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(r.getAge());

});

executorService.execute(()->{

try {

Thread.sleep(5000);

c.countDown();

} catch (InterruptedException e) {

e.printStackTrace();

}

r.setAge(200);

});

//关闭线程池

executorService.shutdown();

}

}

class Rumenzz{

private Integer age=0;

public synchronized Integer getAge() {

return age;

}

public synchronized void setAge(Integer age) {

this.age = age;

}

}

【Java】多线程之线程可见性synchronized

以上是 【Java】多线程之线程可见性synchronized 的全部内容, 来源链接: utcz.com/a/93063.html

回到顶部