Java learning-multi-threaded creation: anonymous internal class to achieve thread creation

Anonymous internal class method to realize thread creation.
Role: simplify the code
. Inherit the subclass from the parent class, rewrite the parent class method, create the subclass object synthesis, and complete
the implementation class to implement the interface, rewrite the method in the interface, and create the implementation class object synthesis. One step to complete
the final product of the anonymous inner class: subclass/implementation class object, and this class has no name

  格式:
        new 父类/接口() {
    
    
            重写父类方法
        };

Program demonstration

 public static void main(String[] args) {
    
    
        //线程的父类是Thread
        //new MyThread().start();
        new Thread(){
    
    
            @Override
            public void run() {
    
    
                for (int i = 0; i < 10; i++) {
    
    
                    System.out.println(Thread.currentThread().getName()+ "-->"+i);
                }
            }
        }.start();

        //线程的接口
        Runnable r = new Runnable(){
    
    

            @Override
            public void run() {
    
    
                for (int i = 0; i < 10; i++) {
    
    
                    System.out.println(Thread.currentThread().getName()+ "-->"+"程序员");
                }
            }
        };
        new Thread(r).start();
        //接口的线程简化
        new Thread(new Runnable(){
    
    

            @Override
            public void run() {
    
    
                for (int i = 0; i < 10; i++) {
    
    
                    System.out.println(Thread.currentThread().getName()+ "-->"+"林枫");
                }
            }
        }).start();
    }

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/106719751