参考:《Java 网络编程》
回调的应用一直不太熟,今天再看了一下,测试如下:
功能:ListCallbackDigestUserInterface.java 用户类,对用户键入的文件做SHA摘要计算,通过线程来实现,创建一个线程来处理,处理完毕以后会回调调用类的digestCalculated方法显示。主线程不必轮询。
接口类:interface DigestListener
public interface DigestListener {
public void digestCalculated(byte[] digest);
}
线程类:ListCallbackDigest
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;
public class ListCallbackDigest implements Runnable {
private File input;
List listenerList = new Vector();
public ListCallbackDigest(File input) {
this.input = input;
}
public synchronized void addDigestListener(DigestListener l) {
listenerList.add(l);
}
public synchronized void removeDigestListener(DigestListener l) {
listenerList.remove(l);
}
private synchronized void sendDigest(byte[] digest) {
ListIterator iterator = listenerList.listIterator();
while (iterator.hasNext()) {
DigestListener dl = (DigestListener) iterator.next();
dl.digestCalculated(digest);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
FileInputStream in = new FileInputStream(input);
MessageDigest sha = MessageDigest.getInstance("SHA");
DigestInputStream din = new DigestInputStream(in, sha);
int b;
while ((b = din.read()) != -1);
din.close();
byte[] digest = sha.digest();
this.sendDigest(digest);
} catch (IOException e) {
System.err.println(e);
} catch (NoSuchAlgorithmException e) {
System.err.println(e);
}
}
}
主线程类:ListCallbackDigestUserInterface
import java.io.File;
public class ListCallbackDigestUserInterface implements DigestListener {
private File input;
private byte[] digest;
public ListCallbackDigestUserInterface(File input) {
this.input = input;
}
public void calculateDigest() {
ListCallbackDigest cb = new ListCallbackDigest(input);
cb.addDigestListener(this);
Thread t = new Thread(cb);
t.start();
}
@Override
public void digestCalculated(byte[] digest) {
// TODO Auto-generated method stub
this.digest = digest;
System.out.println(this);
}
public String toString() {
String result = input.getName() + ": ";
if (digest != null) {
for (int i = 0; i < digest.length; i++) {
result += digest[i] + " ";
}
} else {
result += "digest not available";
}
return result;
}
public static void main(String[] args) {
for (int i = 0; i < args.length; i++) {
//计算摘要
File f = new File(args[i]);
ListCallbackDigestUserInterface d = new ListCallbackDigestUserInterface(f);
d.calculateDigest();
}
}
}