匿名內部類實現線程的兩種方式


 匿名內部類的使用:  匿名內部類就相當於是   創建了一個子類對象: 編譯時看父類,即Thread類,運行時看子類,及重寫的run(){}方法

1、  繼承Thread 

public class demon1 {
    public static void main(String[] args) {
        Thread t1 = new Thread(){         // t1是一個線程對象, 暫時沒有線程名。 可以通過t1.setName(name)設置線程名  
            @Override
            public void run() {
                System.out.println(this.getName() + ".......aaaaaa");
                super.run();
            }
            
        };
        new Thread(){       //   可以在構造方法里傳入一個值,這個值就是線程名
            @Override
            public void run() {
                this.setName("lisoi");   // 在方法里 設置線程名
                System.out.println(this.getName() + "......bb");
                super.run();
            }
            
        }.start();
        t1.setName("zhangsan");
        t1.start();
    }
}

 

 

2、實現Runnable接口

public class demon2_currentThread {

    public static void main(String[] args) {
        new Thread("t1"){    //  直接傳入 線程名字

            @Override
            public void run() {
                System.out.println(getName() + "......aaaa"); // getName() 獲取線程名
                
            }
            
        }.start();   //  start 直接開啟線程        
        new Thread(new Runnable(){
            public void run() {
                System.out.println(Thread.currentThread().getName()+ "......bb"); 
               // Runnable接口方式的多線程,不能直接調用Thread 的方法 , 需要通過Thread.currentThread() 返回對當前正在執行的線程的對象的引用。 再來調用Thread的方法
            }
        }).start();
        System.out.println(Thread.currentThread().getName());       
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM