为了账号安全,请及时绑定邮箱和手机立即绑定

java 多线程的一个奇怪的问题

java 多线程的一个奇怪的问题

呼如林 2019-04-27 22:20:04
先上代码: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,这样不就可以退出循环了嘛?
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 1056 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信