2、回调(Callback)
此方法更为简单、有效。线程通过调用一个主类中的方法来实现这个技术,该方法是由Server主类启动的。当
线程完成任务时,会回调他的创建者。通过回调方法,主程序可以在等待线程结束任务时进行休眠,并且不会
掠夺运行的线程时间。
public class MonitorThread implements Runnable{
private File input;
private byte[] digest;
private Server server;
public MonitorThread (File input,Server server){
this.input = input;
this.server = server;
}
public void run(){
try{
FileInputStream in = new FileInputStream(input);
java.security.MessageDigest sha = MessageDigest.getInstance("SHA");
java.security.DigestInputStream din = new java.security.DigestInputStream(in,sha);
int b;
while((b = din.read()) != -1);
din.close();
digest = sha.digest();
server.receiveDigest(digest);
}
catch(IOException e){
System.err.println(e);
}
catch(NoSuchAlgorithmException e){
System.err.println(e);
}
}
}
====================================================================
public class Server {
private File input;
private byte[] digest ;
public Server(File input){
this.input = input;
}
public void begin
Digest(){
MonitorThread monitorThread = new MonitorThread(inpu,this);
Thread t = new Thread(monitorThread);
t.start();
}
public String toString(){
String result = input.getName() + ":";
if(digest!=null){
for(int i=0;i<digest.length;i++){
result +=digest
+ "";
}
}
return result;
}
public static void main(String args[]){
for(int i=0;i<args.length;i++){
File file=new File(args);
Server server = new Server(file);
server.begin
Digest();
}
}
}
终于写完了,希望对您有所帮助吧![]