Thread调用start和run的区别

本文深入探讨了Java中线程的正确启动方式,强调了应当使用Thread类的start方法而非直接调用run方法。解析了start方法的工作原理,包括线程状态的变化、线程组的加入以及线程的并发执行。同时,通过示例代码展示了如何获取当前线程的所有子线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习Thread的第一天就知道要调用Thread的start方法,不要调用Thread额run方法,为什么呢?
新建一个Thread类的实例,然后调用run方法,相当于调用普通的方法,属于当前线程的一个方法执行,可以重复多次调用,run方法运行结束, 此线程终止, 而CPU再运行其它线程。
run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码;如果直接用run方法, 这只是调用一个方法而已, 程序中依然只有主线程这一个线程, 其程序执行路径还是只有一条。上面的结论可以得出线程的模型,线程栈是指某时刻时内存中线程调度的栈信息,当前调用的方法总是位于栈顶。当调用Thread的start方法时会生成新的线程,放在单独的线程栈中。

调用start的方法有什么不同呢,调用了start的方法会创建线程,并自动调用run方法:

 /**
     * Causes this thread to begin execution; the Java Virtual Machine
     * calls the <code>run</code> method of this thread.
     * <p>
     * The result is that two threads are running concurrently: the
     * current thread (which returns from the call to the
     * <code>start</code> method) and the other thread (which executes its
     * <code>run</code> method).
     * <p>
     * It is never legal to start a thread more than once.
     * In particular, a thread may not be restarted once it has completed
     * execution.
     *
     * @exception  IllegalThreadStateException  if the thread was already
     *               started.
     * @see        #run()
     * @see        #stop()
     */

    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中的线程都是stared*/
        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 */
            }
        }
    }

private native void start0();

根据上面Thread 中start方法的注释,调用Thread的start方法后会创建一个线程(不同于调用start的当前线程的线程),此时线程还没有运行,是可运行的状态(新建线程的状态)。线程最终会调用本地方法start0,它的内部最终会调用run方法。JVM会在线程启动时调用run方法,此时的线程才处于运行状态。run方法结束时,线程终止。

一个线程只能调用start()方法一次,多次启动一个线程是非法的,因为线程的状态变化从new到running不可逆转,且只会发生一次。
看源码 if (threadStatus != 0)
throw new IllegalThreadStateException();
当重复调用时threadStatus != 0 会抛出异常。

Thread 被添加进了group, ThreadGroup group;
线程一定属于某一个线程组中,线程组中可以有线程对象,也可以有线程组,组中还可以有线程,是一种类似属性结构的结构。
在这里插入图片描述

Thread 方法:
在这里插入图片描述
activeCount 获取当前线程所有活动线程的估计数,因为线程数量是实时改变的。
在这里插入图片描述
enumerate把所有活动线程放入到tarray中。

获取当前main线程内的所有的线程:

package com.sync.demo;

import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

public class Demo1 {

	public static void main(String[] args) {
	
		ThreadDemo demo1 = new ThreadDemo();
		demo1.setName("demo1");
		demo1.start();
		
		Thread thread2 = new Thread(new RunnableDemo());
		thread2.setName("demo1");
		thread2.start();
		
		FutureTask<String> thread3 = new FutureTask<>(new Callable<String>() {

			@Override
			public String call() throws Exception {
				try {
					Thread.sleep(3000);
				} catch (Exception e) {
					// TODO: handle exception
				}
				return "demo3";
			}
		});
		
		new Thread(thread3).start();
		
		//or  Executors.newSingleThreadExecutor().execute(thread3);
		findAllThread();
		
	}
	
	public static class ThreadDemo extends Thread{
		@Override
		public void run() {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("demo1");
		}
	}
	
	public static class RunnableDemo implements Runnable{
		@Override
		public void run() {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("demo2");
			
		}
	}
	
	
	public static Thread[] findAllThread(){
		  ThreadGroup currentGroup =Thread.currentThread().getThreadGroup();

		  //找到最终的父线程组
		  while (currentGroup.getParent()!=null && currentGroup.getParent().getName().equals("main")){
		      currentGroup=currentGroup.getParent();
		  }
		  //活动线程的估计数
		  int noThreads = currentGroup.activeCount();

		  Thread[] threadArray = new Thread[noThreads];
		  //复制到指定数组中。
		  currentGroup.enumerate(threadArray);

		  for (Thread thread : threadArray) {
		      System.out.println("线程数量:"+noThreads+" 线程id:" + thread.getId() + " 线程名称:" + thread.getName() + " 线程状态:" + thread.getState());
		  }
		  return threadArray;
		}

}

Result:

线程数量:4 线程id:1 线程名称:main 线程状态:RUNNABLE
线程数量:4 线程id:11 线程名称:demo1 线程状态:TIMED_WAITING
线程数量:4 线程id:12 线程名称:demo1 线程状态:TIMED_WAITING
线程数量:4 线程id:13 线程名称:Thread-2 线程状态:TIMED_WAITING
demo1
demo2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值