package com.javarush.test.level20.lesson07.task05;
import java.io.*;
/* Переопределение сериализации
Сделайте так, чтобы после десериализации нить runner продолжила работать.
Ключевые слова объекта runner менять нельзя.
Hint/Подсказка:
Конструктор не вызывается при сериализации, только инициализируются все поля.
*/
public class Solution implements Serializable, Runnable {
transient private Thread runner;
private int speed;
public Solution(int speed) {
this.speed = speed;
startThread();
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Solution savedObject = new Solution(1000);
Thread.sleep(5000);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("20-07-05.txt"));
oos.writeObject(savedObject);
oos.flush();
oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("20-07-05.txt"));
Solution loadedObject = (Solution) ois.readObject();
System.out.println(loadedObject.speed);
}
public void run() {
// do something here, does not matter
while (true) {
System.out.println("he-he ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
Переопределяем сериализацию.
Для этого необходимо объявить методы:
private void writeObject(ObjectOutputStream out) throws IOException
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
Теперь сериализация/десериализация пойдет по нашему сценарию 🙂
*/
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
startThread();
}
private void startThread() {
runner = new Thread(this);
runner.start();
}
}
Leave A Comment