Link to home
Start Free TrialLog in
Avatar of JianJunShen
JianJunShen

asked on

When thread is destroyed Java

I have following codes. In the main method, I start two threads. How could I detect when thread finnish its mission/is destroyed?
public class CounterThread extends Thread {
	
	public CounterThread(String name){
		super(name);
	}

	public void run(){
		int limit=0;
		while(limit<250){
			limit++;
			try{
			  Thread.sleep(30);
			}catch(InterruptedException ie){
				ie.printStackTrace();
			}
		    synchronized(Counter.getInstance()){	
			   increaseCounter();
			   print(Counter.getInstance());
		    }   		
		}
	}
	
	public void increaseCounter(){
		Counter.getInstance().increaseCounter();
	}
	
    public void print(Counter counter){
    	System.out.println("Thread "+getName()+" is running :Counter now is: "+counter.getCounter());
    	
    }
    
  
    public static void main(String[] args){
        CounterThread ct1 = new CounterThread("ct1");
        CounterThread ct2 = new CounterThread("ct2");
         
        ct1.start();
        ct2.start();
 
    }
}

Open in new window

Avatar of klymptzic
klymptzic

Use, isAlive() with join() method

Below URL has the example to determine when a thread has finished

http://www.exampledepot.com/egs/java.lang/IfStopped.html
By adding a 'finalize()' overload method.

This method (in any class) is called when the GC finally destroys an object.

;JOOP!
My solution applies to any class everywhere.
You might put a logging message in it to record the destruction.

;JOOP!
Avatar of JianJunShen

ASKER

but the problem is that I have a number of thread, hwo to detect the last thread is destroyed?
ASKER CERTIFIED SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
each time you create a thread and start it, add its reference into a ArrayList.

After the last thread is created, start browsing your arraylist and do a isAlive() test to check if you've got thread running, each a thread is finishing
The answer touches the point. It is clear and solving the problem!! Thanks!!!