Java中volatile和transient之间的区别
volatile关键字用于多线程环境中,其中两个线程同时读取和写入同一变量。volatile关键字将更改直接刷新到主内存,而不是CPU缓存。
另一方面,在序列化过程中使用了transient关键字。标记为瞬态的字段不能成为序列化和反序列化的一部分。我们不想保存任何变量的值,那么我们将瞬态关键字与该变量一起使用。
瞬态示例
// 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);
}
}热门推荐
10 毛笔哥哥结婚祝福语简短
11 向国庆送祝福语简短
12 建队节祝福语简短
13 朋友喜得外孙简短祝福语
14 小店营业的祝福语简短
15 餐饮生日祝福语简短独特
16 鲜花英语祝福语卡片简短
17 男朋友暴富祝福语简短
18 婶婶拜年祝福语大全简短