1.对象流
序列化:将对象存储到硬盘中 反序列化:将对象从硬盘中读取到程序中
先建一个Student类,写好有参无参构造,setget,toString。
Student类中的注意事项:
//这里需要实现一个序列化接口后续才不会报错 public class Student implements Serializable { private String name; //transient:顺化,该变量不参与序列化与反序列化 private transient Integer age;
在另一个类里应用:
//字节流 OutputStream os=new FileOutputStream("D:\\e.txt"); //对象流 ObjectOutputStream oos=new ObjectOutputStream(os); //通过对象流输出一个对象 oos.writeObject(new Student("zs",12)); oos.close(); os.close(); InputStream os1=new FileInputStream("D:\\e.txt"); ObjectInputStream oos1=new ObjectInputStream(os1); Object o=oos1.readObject(); System.out.println(o);//此时输出Student{name='zs', age=null} os1.close(); oos1.close();
2.线程,在方法里创建,main本身就是一个线程
应用程序&进程&线程
应用程序:泛指执行的运行APP
进程:具有一定资源的内存空间,一个应用程序包含n个进程
线程:进程的执行单元,一个进程包含n个线程
(1)创建线程:lambda
Thread t2=new Thread(()->{ for (int i = 0; i < 10; i++) { System.out.println("阿达"+i); } }); t2.start(); 多个线程同时执行他们的输出顺序是随机的
(2)线程优先级
t2.setPriority(10);//最高优先级
(3)sleep
Thread t=new Thread(()->{ System.out.println(111); try {//使程序睡眠3秒再执行 Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(222); }); t.start();
(4)守护线程setDaemon(true)
Thread rose=new Thread(()->{ for (int i = 0; i < 5; i++) { System.out.println("ge"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("寄"); }); Thread jack=new Thread(()->{ while (true){ System.out.println("yougoigo"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } }); //把jack设置为守护线程,即其他线程结束jack也必须结束,即使他是死循环 jack.setDaemon(true); rose.start(); jack.start();
(5)等待方法join()
//在哪个线程写哪个线程等待,等待join所修饰的线程 Thread downnload=new Thread(()->{ for (int i = 1; i <=10 ; i++) { System.out.println("已下载"+i+"%"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }); //join():等待线程结束 Thread show=new Thread(()->{ try {//在此处指等待download执行完后再执行show downnload.join(); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 1; i <=10 ; i++) { System.out.println("当前已经显示"+i+"%"); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } }); downnload.start(); show.start();
(6)锁synchronized
Thread t1=new Thread(()->{ buy("女"); }); Thread t2=new Thread(()->{ buy("男"); }); t1.start(); t2.start(); } static Object ob=new Object(); public static void buy(String name){ System.out.println(name+"挑衣服"); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //加锁,此时试衣间只能进一个人 //不加锁会出现两个人都进了试衣间 synchronized (ob){ System.out.println(name+"试衣服");} try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(name+"结账");