简体   繁体   中英

How to add a lifecycle to a Thread that starts with "new Thread(new Runnable)..."?

Most examples of lifecycles for a Thread tend to be about threads in which you first instantiate them some way:

Thread t = new Thread();

Then you can refer to that thread in the lifecycle by saying stuff like:

t.join();

or something like that.

But how to do add the proper lifecyle when you have not physically instantiated the Thread, such as you start: new Thread(new Runnable)...

public static void main(String[] args) {
    System.out.println("Before instantiation of thread");
    new Thread(new Runnable(){
        @Override
        public void run() {
            System.out.println("Thread State ::" + Thread.currentThread().getState());
            for(int i=0;i<100;i++){
                try {
                    Thread.sleep(1000);
                    System.out.println("Thread State ::" +i);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                System.out.println("Thread State ::" + Thread.currentThread().getState());
            }
        }
    }).start();
    System.out.println("After instantiation of thread");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM