How to start anonymous thread class

前端 未结 8 745
清歌不尽
清歌不尽 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:01

    You're already creating an instance of the Thread class - you're just not doing anything with it. You could call start() without even using a local variable:

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

    ... but personally I'd normally assign it to a local variable, do anything else you want (e.g. setting the name etc) and then start it:

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

提交回复
热议问题