如何将生命周期添加到以"new Thread(new Runnable)..."开头的线程?



线程生命周期的大多数例子往往是关于你以某种方式第一次实例化它们的线程:

Thread = new Thread();

然后你可以在生命周期中引用这个线程,比如:

t.join ();

之类的

但是如何添加适当的生命周期,当你没有物理实例化线程,比如你开始:

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");
}

最新更新