volatile关键字用于多线程环境中,其中两个线程同时读取和写入同一变量。volatile关键字将更改直接刷新到主内存,而不是CPU缓存。
另一方面,在序列化过程中使用了transient关键字。标记为瞬态的字段不能成为序列化和反序列化的一部分。我们不想保存任何变量的值,那么我们将瞬态关键字与该变量一起使用。
| 序号 | 键 | 易挥发的 | 短暂的 |
|---|---|---|---|
| 1 | 基本的 | Volatile关键字用于将更改直接刷新到主内存 | 瞬态关键字用于在序列化期间排除变量 |
| 2。 | 默认值 | 挥发性不使用默认值初始化。 | 反序列化期间,将使用默认值初始化瞬态变量 |
| 3 | 静态的 | 易失性可以与静态变量一起使用。 | 暂时不能与static关键字一起使用 |
| 4 | 最后 | 可以与final关键字一起使用 | 瞬态不能与final关键字一起使用 |
// A sample class that uses transient keyword to
//跳过其序列化。
class TransientExample implements Serializable {
transient int age;
//序列化其他字段
private String name;
private String address;
//其他代码
}class VolatileExmaple extends Thread{
boolean volatile isRunning = true;
public void run() {
long count=0;
while (isRunning) {
count++;
}
System.out.println("线程终止。" + 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);
}
}