Click here to Skip to main content
15,881,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It's me again. I have some problem here. Here is the code

C#
class Thread1 extends Thread {
    int i=0;
    public void run(){
            try{
                for(i=0; i<10; i++){
                    System.out.println("Print this 10 times");
                    System.out.println("Timer: "+(i+1));
                    Thread.sleep(1000);
                }
            }
            catch(Exception ex){}
        }
    }

class Thread2 extends Thread {
    public void run(){
        try{
            for(int i=0; i<10; i++){
                System.out.println("Timer: "+(i+1));
                Thread.sleep(1000);
            }
        }
        catch(Exception ex){}
    }
}


Each thread run in 10 seconds.

Now is must create the main thread with this request: Execute the program and run the Thread1 first. Then at 5 seconds, stop Thread1 and run Thread2. Then terminate the program at 10 seconds. And of course: without touching Thread1 and Thread2.

I tried System.currentTimeMillis() but no luck. Are there any other way to measure the thread's running time and stop it at specific point?

Thank you very much!
Posted
Updated 1-Jun-13 2:22am
v3

You should put the thread termination logic in the thread's code and handle termination condition(s) there instead of monitoring externally and killing off threads from the parent process. Threads (and fibers and processes) can do bad things if not terminated gracefully. If you implement 'hari kari' logic within a thread, it will be able to clean itself up and tie up loose ends before dying.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900