java的匿名内部类

我们都知道java的接口是不能实例化的,而我们都知道Runnable是一个接口,在多线程的时候经常会看到这样的代码new Thread(new Runnable(void run(){...}));这时候就困惑了。

其实这不是实例化Runnable接口,而是先创建一个实现Runnable接口的没有名字的类之后再实例化这个新的类,{...}是这个类的内容。而Thread方法有个构造函数是需要传入实现Runnable类的参数的  public Thread(Runnable target) 。

然而为什么把另一个线程要执行的内容放在run方法里,然后Thread对象start一下就执行了呢?

我原以为start()方法里调用run()了,

模拟一下,就像这样

public interface myRunnable {
    void run();
}

public class Thread {
   myRunnable p;
   public Thread(myRunnable p)
   {
  this.p = p;
   }
   public void start()
   {
  p.run();
   }
   public static void main(String[] args)
   {
  Thread w =new Thread(new myRunnable()
  {
  public void run()
  {
  System.out.println("run");
  }
  });
  w.start();
   }
}

其实不然,

以下是jdk中的start方法,

 public synchronized void start() {
        /**
         * This method is not invoked for the main method thread or "system"
         * group threads created/set up by the VM. Any new functionality added
         * to this method in the future may have to also be added to the VM.
         *
         * A zero status value corresponds to state "NEW".
         */
        if (threadStatus != 0)
            throw new IllegalThreadStateException();


        /* Notify the group that this thread is about to be started
         * so that it can be added to the group's list of threads
         * and the group's unstarted count can be decremented. */
        group.add(this);


        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

start调用了start0本地方法,然后新产生一个线程调用run方法,见http://blog.csdn.net/xiancaieeee/article/details/7767895

补充一下,以前一直搞不清楚多线程怎样控制一个对象,其实只要多new几次Thread每次传入一个同一个对象即可,这样可以实现多个线程共享同一个目标对象,非常适合处理同一个资源的情况(相对于继承Thread类的优点),在run方法中如果访问当前进程必须用,Thead.currentThread()方法,而继承Thread方法直接使用this可以获得当前线程。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值