线程的run()方法带参情况

首先看一下Runnable接口的源码,整个方法体里就只有一个run的抽象方法,所以才创建实现类实现该接口的时候是肯定要重写接口内的抽象方法的(也就是run()方法),按照重写规则(不能是抽象,参数要和父类一致,也就是无参)重写run()方法,方法体就可以自定义添加了。

@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

但是我在百度上找到了这么一个题
在这里插入图片描述
能看到run()方法的参数是Thread t,并不是无参但是能够成功运行,以下是run()方法可以带参的情况:

要实现带参数的run()方法

  1. 定义线程内变量;
  2. 在继承thread的时候,增加带参数的构造函数,初始化线程内变量;
  3. 在run方法操作线程内变量,以达到类似传参的效果。

示例:

class MyThread extends Thread{
    int a = 0;//定义线程内变量
    public MyThread(int a){//定义带参数的构造函数,达到初始化线程内变量的值
       this.a=a;
    }
    @Override
    public void run() {
        this.a++;//线程内变量自增
    }
}

引用一位网友的回答补充说明这里是引用

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值