How to start anonymous thread class

前端 未结 8 764
清歌不尽
清歌不尽 2020-12-04 15:37

I have the following code snippet:

public class A {
    public static void main(String[] arg) {
        new Thread() {
            public void run() {
               


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 15:51

    Since anonymous classes extend the given class you can store them in a variable.

    eg.

    Thread t = new Thread()
    {
        public void run() {
            System.out.println("blah");
        }
    };
    t.start();
    

    Alternatively, you can just call the start method on the object you have immediately created.

    new Thread()
    {
        public void run() {
            System.out.println("blah");
        }
    }.start();
    // similar to new Thread().start();
    

    Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).

    eg

    new Thread(new Runnable()
    {
        @Override
        public void run() {
            System.out.println("blah");
        }
    }).start();
    

提交回复
热议问题