发表日期: 2022-03-23 11:09:28 浏览次数:111
亳州网页制作

transient
当对象被序列化时(写入字节序列到目标文件)时,transient阻止实例中那些用此关键字声明的变量持久化;当对象被反序列化时(从源文件读取字节序列进行重构),这样的实例变量值不会被持久化和恢复。
import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;//定义一个需要序列化的类class People implements Serializable{
String name; //姓名
transient Integer age; //年龄
public People(String name,int age){
this.name = name;
this.age = age;
}
public String toString(){
return "姓名 = "+name+" ,年龄 = "+age;
}}public class TransientPeople {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
People a = new People("李雷",30);
System.out.println(a); //打印对象的值
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("d://people.txt"));
os.writeObject(a);//写入文件(序列化)
os.close();
ObjectInputStream is = new ObjectInputStream(new FileInputStream("d://people.txt"));
a = (People)is.readObject();//将文件数据转换为对象(反序列化)
System.out.println(a); // 年龄 数据未定义
is.close();
}}运行结果如下:
姓名 = 李雷 ,年龄 = 30姓名 = 李雷 ,年龄 = null
volatile
volatile可以用在任何变量前面,但不能用于final变量前面,因为final型的变量是禁止修改的。
使用的场景之一,单例模式中采用DCL双锁检测(double checked locking)机制,在多线程访问的情况下,可使用volatitle修改,保证多线程下的可见性。缺点是性能有损失,因此单线程情况下不必用此修饰符。
class Singleton{
private volatile static Singleton instance = null;
private Singleton() {
}
public static Singleton getInstance() {
if(instance==null) {
synchronized (Singleton.class) {
if(instance==null)
instance = new Singleton();
}
}
return instance;
}}