Java线程停止通知程序
发布时间:2020-12-15 04:26:19 所属栏目:Java 来源:网络整理
导读:我的任务是使用多个线程执行解压缩操作.我用以下结构方式做到了. // A class for Unzipping filespublic class UnzipClass extends Thread(){ private String zipfile; private Thread t; public UnzipClass(String zipFile){ this.zipFile = zipFile; } pub
我的任务是使用多个线程执行解压缩操作.我用以下结构方式做到了.
// A class for Unzipping files public class UnzipClass extends Thread(){ private String zipfile; private Thread t; public UnzipClass(String zipFile){ this.zipFile = zipFile; } public String getZipFile() { return zipFile; } public void setZipFile(String zipFile) { this.zipFile = zipFile; } public void run() { try { unzipFolder(this.getZipFile()); } catch (IOException ex) { Logger.getLogger(Unzipper.class.getName()).log(Level.SEVERE,null,ex); } } public void start(String filename){ if (t == null){ t = new Thread(this,filename); t.start(); } } public unzipFolder(String zipFile) throws ZipException,IOException // Here is the Unzip Method } } // Now I am calling this class from another class public static void main(){ Thread t1 = new UnzipClass("filename1"); t1.start(); if(!(t1.isAlive())){ logEvent("Unzip Complete"); } // Similarly I have Thread t2 with another file name } 上面的代码工作完美并解压缩文件,但我有以下问题. >我想使用implements Runnable,但我不能使用它,因为我没有找到一种方法将变量(Filename)传递给另一个实现Runnable的类并执行它.从字面上看:如何实现Runnable而不是extends Thread` 任何类型的提示或解决方案都会非常棒. 提前致谢. 解决方法
1.更改
public class UnzipClass extends Thread 到 public class UnzipClass implements Runnable 并使用 Runnable t1 = new UnzipClass("filename1"); 创建线程. 2. while((t1.isAlive())){ logEvent("Unziping..."); } logEvent("Unzip Complete"); 但是在UnzipClass中使用像boolean isComplete这样的标志会更有效.喜欢 在类UnzipClass中添加 private boolean complete=false; 然后, public void run() { try { unzipFolder(this.getZipFile()); complete=true; } catch (IOException ex) { Logger.getLogger(Unzipper.class.getName()).log(Level.SEVERE,ex); } } //simple getter. public boolean isComplete() { return this.complete; } 主… while(!t1.isComplete()){ logEvent("Unziping..."); } logEvent("Unzip Complete"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |