多线程基础-两种多线程实现方式区别

两种多线程实现方式区别


1、继承Thread 来生成多线程对象时,我们需要重写 run 方法,因为 Thraed类的run 方法什么也没做

源码分析
Thread t1= new Thread1();

    构造方法:这里的target为空
    public Thread() {
          init(null, null, "Thread-" + nextThreadNum(), 0);
    }
1、当实现Runnable 接口时,这是线程对象的run方法执行的是接口 Runnable 的run 方法

Thread t4= new Thread(new Runnable);

    构造方法:这里的target 不为空
    public Thread(Runnable target) {
          init(null, target, "Thread-" + nextThreadNum(), 0);
    }
 * 源码实现:
 *  public Thread(Runnable target) {
 *         init(null, target, "Thread-" + nextThreadNum(), 0);
 *     }
   ```java
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize) {
          init(g, target, name, stackSize, null);
    }
    private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name.toCharArray();

        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            if (security != null) {
                g = security.getThreadGroup();
            }            
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }     
        g.checkAccess();      
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }
        g.addUnstarted();
        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        //请看这里,将构造方法的target 赋值给了 本类的成员变量 target
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);

        this.stackSize = stackSize;


        tid = nextThreadID();
    }
//run 方法  如果target为空 什么也不做 
@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值