咋一看貌似挺简单,但是涉及了对象的序列化与反序列化,线程之间的通信与同步。
当时我的做法是,写了两个线程类A和B,一个ThreadPool类,A和B的实例创建都要放进ThreadPool里。A在它的生命周期里负责在ThreadPool获取出B的实例,调用其提供的setXXX方法将对象传入,B则一直等待XXX的传入,一旦传入,就结束循环,将值打印。这样的做法显然不符合第一个要求,而且也没用到提供的byte数组,感觉怪怪的。于是今晚经过一番调研之后,重新写了一遍。代码如下:
//线程通信数据类,实现Serializable接口以便序列化
class Employee implements java.io.Serializable {
privateString name;
publicEmployee(String name) {
this.name = name;
}
publicString getName() {
return name;
}
publicvoid setName(String name) {
this.name = name;
}
}
class A extends Thread {
privatestatic byte[] b = new byte[255]; //公用数据区
publicA(String name) {
super(name);
}
publicvoid run() {
if(this.getName().equals("A")) {
synchronized (b) { //将b加锁
try {
b = ByteUtil.getBytes(newEmployee("pany"));//new 一个E对象并序列化成字节数组
System.out.println("inA");
sleep(2000);
} catch(InterruptedException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null, ex);
} catch(IOException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null, ex);
}
}
} else if(this.getName().equals("B")) {
synchronized (b) {
try {
Employee e = (Employee)ByteUtil.getObject(b);//反序列化为E
System.out.println(e.getName());
sleep(2000);
} catch(InterruptedException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null, ex);
} catch(IOException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null, ex);
} catch(ClassNotFoundException ex) {
Logger.getLogger(A.class.getName()).log(Level.SEVERE,null, ex);
}
}
}
}
public class MyThread {
publicstatic void main(String[] args) {
A a = new A("A");
A b = new A("B");
a.start();
b.start();
}
}
//工具类,序列化对象与反序列化对象
class ByteUtil {
publicstatic byte[] getBytes(Object obj) throws IOException {
ByteArrayOutputStream bout =new ByteArrayOutputStream();
ObjectOutputStream out = newObjectOutputStream(bout);
out.writeObject(obj);
out.flush();
byte[] bytes =bout.toByteArray();
bout.close();
out.close();
return bytes;
}
publicstatic Object getObject(byte[] bytes) throws IOException,ClassNotFoundException {
ByteArrayInputStream bi = newByteArrayInputStream(bytes);
ObjectInputStream oi = newObjectInputStream(bi);
Object obj =oi.readObject();
bi.close();
oi.close();
return obj;
}
}