How to start anonymous thread class

前端 未结 8 719
清歌不尽
清歌不尽 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 16:05

    Not exactly sure this is what you are asking but you can do something like:

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

    Notice the start() method at the end of the anonymous class. You create the thread object but you need to start it to actually get another running thread.

    Better than creating an anonymous Thread class is to create an anonymous Runnable class:

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

    Instead overriding the run() method in the Thread you inject a target Runnable to be run by the new thread. This is a better pattern.

    0 讨论(0)
  • 2020-12-04 16:05

    The entire new expression is an object reference, so methods can be invoked on it:

    public class A {
        public static void main(String[] arg)
        {
            new Thread()
            {
                public void run() {
                    System.out.println("blah");
                }
            }.start();
        }
    }
    
    0 讨论(0)
提交回复
热议问题