java 中 volatile 和 temporary 的区别

javaobject oriented programmingprogramming更新于 2024/5/2 15:08:17

在多线程环境中使用 volatile 关键字,其中两个线程同时读取和写入同一变量。 volatile 关键字将更改直接刷新到主内存而不是 CPU 缓存。 

另一方面,transient 关键字在序列化期间使用。 标记为 temporary 的字段不能成为序列化和反序列化的一部分。 如果我们不想保存任何变量的值,那么我们对该变量使用 temporary 关键字。 

Sr.不。KeyVolatileTransient
1
Basic 
Volatile关键字用于将更改直接刷新到主内存
transient关键字用于在序列化期间排除变量 
2.
默认值
Volatile 未使用默认值进行初始化。
在反序列化过程中,transient 变量会使用默认值进行初始化
3
Static 
Volatile 可以与静态变量一起使用。
Transient 不能与 static 关键字一起使用
4
Final 
Volatile 可以与 final 关键字一起使用
Transient 不能与 final 一起使用关键字

Transient 示例

// 使用 temporary 关键字的示例类
// 跳过序列化。
class TransientExample implements Serializable {
   transient int age;
   // 序列化其他字段
   private String name;
   private String address;
   // 其他代码
}

Volatile 示例

class VolatileExmaple extends Thread{
   boolean volatile isRunning = true;
   public void run() {
      long count=0;
      while (isRunning) {
         count++;
      }
      System.out.println("Thread terminated." + count);
   }
   public static void main(String[] args) throws InterruptedException {
      VolatileExmaple t = new VolatileExmaple();
      t.start();
      Thread.sleep(2000);
      t.isRunning = false;
      t.join();
      System.out.println("isRunning set to " + t.isRunning);
   }
}

相关文章


有用资源