JAVA多线程的变量共享

//非同步共享变量
public class Novisibility{
  private static boolean ready;
  private static int number;

  //创建线程,当ready值为true的时候,输出number值
  private static class ReaderThread extends Thread{
    public void run(){
      while(!ready){
        Thread.yield();
      }
      System.out.println(number);
    }
  }
 
  public static void main(String[] args){
    new ReaderThread().start();
    ready = true;
    number = 30;
  }
}

该线程会持续循环下去,因为读线程可能永远都看不到ready值,另一种更奇怪的现象,可能会输出0,因为读线程
可能看到了ready值,但是没有看到之后写入的number值。

//非线程安全的可变整数类
@NotThreadSafe
public class MutableInteger{
  private int value;

  public int get(){
    return value;
  }

  public void set(int value){
    this.value = value;
  }
}

该对象不是线程安全的,方法没有做同步的情况下,当某个线程调用set方法的时候,另一个正在调用get的线程可能会看到更新后的value值,也可能看不到

//线程安全的可变整数类
@ThreadSafe
public class SynchronizedInteger{
  private int value;

  public synchronized int get(){
    return value;
  }

  public synchronized set(int value){
    this.value = value;
  }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值