Search code examples
javamultithreadingrunnable

Java Thread stop notifier


My task here is to perform unzip operation using multiple threads. I did it with following structure Way.

// 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 perfect and unzips the files but I have following problems.

  1. I wanted to use implements Runnable , but I cannot use it because I did not find a way to pass variable(Filename) to another class which implements Runnable and do it. Literally: How to implement Runnable instead of extends Thread`

  2. Using above method, How can I detect if the unzip process has been completed. To be specific how to stop the thread when the file unzip process is completed`.

Any sort of hint or solution would be really great.

Thanks in advance.


Solution

  • 1.change

    public class UnzipClass extends Thread
    

    into

    public class UnzipClass implements Runnable 
    

    and use

    Runnable t1 = new UnzipClass("filename1");
    

    to create the thread.

    2. use a while loop here

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

    but using a flag like boolean isComplete in the UnzipClass will me more effective. like

    in class UnzipClass add

    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, null, ex);
    }
    }
    
    //simple getter.
    public boolean isComplete()
    {
        return this.complete;
    }
    

    in main...

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