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

Java

Avatar of undefined
Last Comment
JianJunShen

8/22/2022 - Mon
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
sciuriware

By adding a 'finalize()' overload method.

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

;JOOP!
sciuriware

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

;JOOP!
Your help has saved me hundreds of hours of internet surfing.
fblack61
JianJunShen

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

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
cho7

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
JianJunShen

ASKER
The answer touches the point. It is clear and solving the problem!! Thanks!!!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.