首页 > 其他 > 详细

Thread对象 既传入了Runnable对象又重写了run()方法

时间:2019-07-27 18:06:22      阅读:96      评论:0      收藏:0      [点我收藏+]

Thread本身是一个类,其run():

正常情况下, target(即传入的new Runnable()对象)不为空,就是执行target里面的run方法

但是,重新run()方法之后,就不会在执行target.run(),除非显示调用: super.run()

    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

 

public class StringTest {
    private static int a;
    private static int b;
    public static void main(String[] args) {
        a = 1;
        b = 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                while (a < 5) {
                    System.out.println("a=" + a);
                    a++;
                    b--;
                }
            }
        }) {
            public void run() {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {

                }
                while (b < 5) {
                    System.out.println("b=" + b);
                    b++;
                    a--;
                }
            };
        }.start();
    }
}

技术分享图片

 

Thread对象 既传入了Runnable对象又重写了run()方法

原文:https://www.cnblogs.com/DDiamondd/p/11255536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!