用匿名子类来启动一个线程

来源:互联网 发布:mindmap mac 破解版 编辑:程序博客网 时间:2024/06/14 16:47
public class Test2 {

    public static void main(String[] args) {
        
        new Thread(new SecondThread()) {
            public void run() {
                System.out.println("hello!boss!");
            };
        }.start();

    }

}
class SecondThread implements Runnable{

 
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("hello!SecondThread!");
    }

}

会后打出来的是hello!boss!

用分步骤写出来就是如下所示:

public class Test2 {

    public static void main(String[] args) {
     
        SecondThread a = new SecondThread();
        Thread1 s = new Thread1(a);
        s.start();
    }

}
class SecondThread implements Runnable{

 
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("hello!SecondThread!");
    }

}

class Thread1 extends Thread{
  
    public void run() {
        System.out.println("hello!boss!");
    }
    public Thread1(Runnable target) {
        super(target);
    }
    
}
匿名类在只是用一次的时候使用