java中的一个线程在java中是无法重启的,所以我实现了一个java Thread,然后在拿到Thread的序列化对象后尝试重启线程。
import java.io.Serializable;
public class ThreadSerialization extends Thread implements Serializable {
int iCheck = 10;
@Override
public void run() {
System.out.println("STARTING");
for(int i=0;i<10;i++){
iCheck+=i;
}
}
}
和序列化算法-
public class CallingThreadSerializable {
public static void main(String[] args) {
ThreadSerialization ser = new ThreadSerialization();
ser.start();
FileOutputStream fos = null;
ObjectOutputStream out = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fos = new FileOutputStream("thread.ser");
out = new ObjectOutputStream(fos);
out.writeObject(ser);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
fis = new FileInputStream("thread.ser");
ois = new ObjectInputStream(fis);
ThreadSerialization ser1 = (ThreadSerialization) ois.readObject();
System.out.println("---> " + ser1.iCheck);
ser1.start();
System.out.println("---> " + ser1.iCheck);
ois.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
输出-
STARTING
---> 55
---> 55
STARTING
为什么 ser1 对象又开始了?