Java thread stop Notifier

My task is to use multiple threads to perform decompression I did it with the following structure

// 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 

 }

The above code works perfectly and decompresses the file, but I have the following problems

>I want to use implements runnable, but I can't use it because I can't find a way to pass a variable (filename) to another class that implements runnable and execute it Literally: how to implement runnable instead of extends Thread ` > using the above method, how to detect whether the decompression process has been completed How to stop the thread when the file decompression process is completed

Any type of tip or solution would be great

Thank you in advance

Solution

1. Change

public class UnzipClass extends Thread

reach

public class UnzipClass implements Runnable

And use

Runnable t1 = new UnzipClass("filename1");

Create a thread

2. Use the while loop here

while((t1.isAlive())){
  logEvent("Unziping...");
} 

logEvent("Unzip Complete");

However, it is more effective to use flags like Boolean iscomplete in UnzipClass like

Add in class UnzipClass

private boolean complete=false;

then,

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;
}

Lord

while(!t1.isComplete()){
  logEvent("Unziping...");
} 

logEvent("Unzip Complete");
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>