synchronized:当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。
instanceof:在运行时指出对象是否是特定类的一个实例。
result = object instanceof class
strictfp:strict float point (精确浮点),保证平台移植之后,浮点运算结果是一致的。
transient:如果用transient声明一个实例变量,当对象存储时,它的值不需要维持。即用transient关键字标记的成员变量不参与序列化过程。
assert:断言可以证明程序的正确性。
assert expression1
assert expression1: expression2
expression1表示一个boolean表达式,expression2表示一个基本类型、表达式或者是一个Object,用于在失败时输出错误信息。
在eclipse中,必须开启相关设置。具体在Window->Preferences->Java->Installed JREs,选择相关版本,点击edit,在Default VM arguments里面输入-ea。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Demo {
public static void main(String[] args) {
People people = new People();
try {
//序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("people.dat"));
oos.writeObject(people);
oos.close();
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("people.dat"));
people = (People) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
//线程
MyRunner boy = new MyRunner(people, "GG", "boy");
MyRunner girl = new MyRunner(people, "MM", "girl");
Thread thread1 = new Thread(boy,"boy");
Thread thread2 = new Thread(girl,"girl");
thread1.start();
thread2.start();
//断言
boolean isPeople = people instanceof People;
assert !isPeople:"it's wrong";
}
}
class People implements Serializable{
private String name;
private String sex;
private transient String school = "FJNU";
public synchronized void set(String name,String sex) {
this.name = name;
this.sex = sex;
}
public void print(){
System.out.println("name="+name+",sex="+sex+",school="+school);
}
}
class MyRunner implements Runnable{
private People people;
private String name;
private String sex;
public MyRunner(People people,String name,String sex) {
this.people = people;
this.name = name;
this.sex = sex;
}
@Override
public void run() {
for(int i=0;i<10;i++){
people.set(name, sex);
people.print();
}
}
}
运行结果如下:
Exception in thread “main” name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=GG,sex=boy,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=MM,sex=girl,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
name=GG,sex=boy,school=null
java.lang.AssertionError: it’s wrong at Demo.main(Demo.java:32)
请读者思考如下问题,欢迎在评论中互动:
如果People的set方法去掉synchronized关键字,结果会怎样?
为什么school是null?
先自我介绍一下,小编13年上师交大毕业,曾经在小公司待过,去过华为OPPO等大厂,18年进入阿里,直到现在。深知大多数初中级java工程师,想要升技能,往往是需要自己摸索成长或是报班学习,但对于培训机构动则近万元的学费,着实压力不小。自己不成体系的自学效率很低又漫长,而且容易碰到天花板技术停止不前。因此我收集了一份《java开发全套学习资料》送给大家,初衷也很简单,就是希望帮助到想自学又不知道该从何学起的朋友,同时减轻大家的负担。添加下方名片,即可获取全套学习资料哦