java new Thread(Runnable) 干了什么?

一直很好奇,new Thread()干了什么?有没有性能消耗
构造方法如下,如果没指定线程名字,默认是 "Thread-" + nextThreadNum() 格式

    /**
     * Allocates a new {@code Thread} object. This constructor has the same
     * effect as {@linkplain #Thread(ThreadGroup,Runnable,String) Thread}
     * {@code (null, target, gname)}, where {@code gname} is a newly generated
     * name. Automatically generated names are of the form
     * {@code "Thread-"+}<i>n</i>, where <i>n</i> is an integer.
     *
     * @param  target
     *         the object whose {@code run} method is invoked when this thread
     *         is started. If {@code null}, this classes {@code run} method does
     *         nothing.
     */
    public Thread(Runnable target) {
        init(null, target, "Thread-" + nextThreadNum(), 0);
    }

跟踪后,最终到了init方法

/**
     * Initializes a Thread.
     *
     * @param g the Thread group
     * @param target the object whose run() method gets called
     * @param name the name of the new Thread
     * @param stackSize the desired stack size for the new thread, or
     *        zero to indicate that this parameter is to be ignored.
     * @param acc the AccessControlContext to inherit, or
     *            AccessController.getContext() if 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) {
            /* Determine if it's an applet or not */

            /* If there is a security manager, ask the security manager
               what to do. */
            if (security != null) {
                g = security.getThreadGroup();
            }

            /* If the security doesn't have a strong opinion of the matter
               use the parent thread group. */
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }

        /* checkAccess regardless of whether or not threadgroup is
           explicitly passed in. */
        g.checkAccess();

        /*
         * Do we have the required permissions?
         */
        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();
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
            this.inheritableThreadLocals =
                ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        /* Stash the specified stack size in case the VM cares */
        this.stackSize = stackSize;

        /* Set thread ID */
        tid = nextThreadID();
    }

从源码可以得知,将当前线程作为父线程,并继承父线程的线程分组、守护线程标识、classloader、栈大小等,并将传入的Runnable参数作赋值给target,在run()方法中,调用了target.run(),所以new Thread(runnableTarget),会执行runnableTarget的run方法

 /**
     * If this thread was constructed using a separate
     * <code>Runnable</code> run object, then that
     * <code>Runnable</code> object's <code>run</code> method is called;
     * otherwise, this method does nothing and returns.
     * <p>
     * Subclasses of <code>Thread</code> should override this method.
     *
     * @see     #start()
     * @see     #stop()
     * @see     #Thread(ThreadGroup, Runnable, String)
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

总结

综上来看,new Thread()没有太大的资源消耗,新分配了一个对象,并继承父线程的优先级、守护标识、线程组等;

Java 中,`Thread` 和 `Runnable` 都与多线程编程相关,但它们的定义和含义有所不同。 `Thread` 类是 Java 中用于创建和操作线程的核心类。每个 `Thread` 对象都代表一个独立的线程,它封装了线程的执行逻辑和状态。通过创建 `Thread` 类的实例并调用其 `start()` 方法,可以启动一个新的线程,该线程会执行 `Thread` 类的 `run()` 方法中的代码。 `Runnable` 是一个接口,它代表一个任务。`Runnable` 接口中只有一个抽象方法 `run()`,用于定义线程要执行的任务逻辑。`Runnable` 本身没有启动线程的能力,需要借助 `Thread` 类来启动。可以将实现了 `Runnable` 接口的对象作为参数传递给 `Thread` 类的构造函数,然后通过 `Thread` 对象的 `start()` 方法来启动线程并执行 `Runnable` 中的 `run()` 方法 [^1][^3]。 以下是简单的代码示例: ```java // 实现 Runnable 接口 class MyRunnable implements Runnable { @Override public void run() { System.out.println("This is a task implemented by Runnable."); } } // 继承 Thread 类 class MyThread extends Thread { @Override public void run() { System.out.println("This is a thread created by extending Thread."); } } public class Main { public static void main(String[] args) { // 使用 Runnable 创建线程 MyRunnable myRunnable = new MyRunnable(); Thread thread1 = new Thread(myRunnable); thread1.start(); // 直接使用 Thread 子类创建线程 MyThread myThread = new MyThread(); myThread.start(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值