In Java, how do you determine if a thread is running?

后端 未结 10 2190
-上瘾入骨i
-上瘾入骨i 2020-11-28 11:30

How do you determine if a thread is running?

10条回答
  •  北海茫月
    2020-11-28 12:25

    Thought to write a code to demonstrate the isAlive() , getState() methods, this example monitors a thread still it terminates(dies).

    package Threads;
    
    import java.util.concurrent.TimeUnit;
    
    public class ThreadRunning {
    
    
        static class MyRunnable implements Runnable {
    
            private void method1() {
    
                for(int i=0;i<3;i++){
                    try{
                        TimeUnit.SECONDS.sleep(1);
                    }catch(InterruptedException ex){}
                    method2();
                }
                System.out.println("Existing Method1");
            }
    
            private void method2() {
    
                for(int i=0;i<2;i++){
                    try{
                        TimeUnit.SECONDS.sleep(1);
                    }catch(InterruptedException ex){}
                    method3();
                }
                System.out.println("Existing Method2");
            }
    
            private void method3() {
    
                for(int i=0;i<1;i++){
                    try{
                        TimeUnit.SECONDS.sleep(1);
                    }catch(InterruptedException ex){}
    
                }
                System.out.println("Existing Method3");
            }
    
            public void run(){
                method1();
            }
        }
    
    
        public static void main(String[] args) {
    
            MyRunnable runMe=new MyRunnable();
    
            Thread aThread=new Thread(runMe,"Thread A");
    
            aThread.start();
    
            monitorThread(aThread);
    
        }
    
        public static void monitorThread(Thread monitorMe) {
    
            while(monitorMe.isAlive())
             {
             try{   
               StackTraceElement[] threadStacktrace=monitorMe.getStackTrace();
    
               System.out.println(monitorMe.getName() +" is Alive and it's state ="+monitorMe.getState()+" ||  Execution is in method : ("+threadStacktrace[0].getClassName()+"::"+threadStacktrace[0].getMethodName()+") @line"+threadStacktrace[0].getLineNumber());  
    
                   TimeUnit.MILLISECONDS.sleep(700);
               }catch(Exception ex){}
        /* since threadStacktrace may be empty upon reference since Thread A may be terminated after the monitorMe.getStackTrace(); call*/
             }
            System.out.println(monitorMe.getName()+" is dead and its state ="+monitorMe.getState());
        }
    
    
    }
    

提交回复
热议问题