先上代码:packageMultithreading;importjavax.xml.bind.DatatypeConverter;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.IOException;importjava.security.DigestInputStream;importjava.security.MessageDigest;importjava.security.NoSuchAlgorithmException;importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.TimeUnit;publicclassThreadUsage{publicstaticvoidmain(String[]args){try{Listfiles=newArrayList();Listworkers=newArrayList();//listfilesincurrentdirectoryfor(Filefile:newFile(".").listFiles()){if(file.isFile())files.add(file.toString());}for(Stringfile:files){DigestThreadworker=newDigestThread(file);workers.add(worker);worker.start();}for(DigestThreadworker:workers){while(worker.digest==null);//TimeUnit.SECONDS.sleep(2);System.out.println(worker.fileName+":"+DatatypeConverter.printHexBinary(worker.digest));}}catch(Exceptione){e.printStackTrace();}}publicstaticclassDigestThreadextendsThread{privateStringfileName;privatebyte[]digest;publicDigestThread(StringfileName){this.fileName=fileName;}@Overridepublicvoidrun(){try{//establishahashfunctionMessageDigestmessageDigest=MessageDigest.getInstance("SHA-256");//usethestreamstofinishthereadandcomputationofeachbyteFileInputStreamfileIn=newFileInputStream(fileName);DigestInputStreamdigestIn=newDigestInputStream(fileIn,messageDigest);while(digestIn.read()!=-1);digestIn.close();fileIn.close();//finishthecomputationdigest=messageDigest.digest();//printmessage//System.out.println(fileName+":"+DatatypeConverter.printHexBinary(digest));}catch(FileNotFoundExceptione){e.printStackTrace();}catch(NoSuchAlgorithmExceptione){e.printStackTrace();}catch(IOExceptione){e.printStackTrace();}}}}main中最后一个foreach循环,如果我选择while语句判断是否完成,运行->一直等待;如果我选择sleep2s,运行->每隔2s输出结果;为什么while循环位卡住呢?每个线程计算完SHA,就赋值digest,这样不就可以退出循环了嘛?
添加回答
举报
0/150
提交
取消