线程八大基础核心二(启动线程)

1.引子

在java多线程并发编程中,有八大基础核心。考考你:看看都有哪八大基础核心呢?它们分别是:

  1.创建线程的方式

  2.线程启动

  3.线程停止

  4.线程生命周期

  5.线程相关的方法

  6.线程相关的属性

  7.线程异常处理

  8.线程安全

今天我们从第二个基础核心开始:启动线程

2.考考你

#前情回顾:

1.在java编程语言中,创建好线程对象后,通过调用start方法,启动线程

Thread t1 = new Thread();

t1.start();

#考考你:

1.问题一:可以调用两次start方法吗?

2.问题二:可以调用run方法,启动线程吗?

3.两次调用start方法

package com.anan.thread.startthread;

/**
 * 两次调用start方法,启动线程
 */
public class TwoStartMethodDemo {

    public static void main(String[] args) {

        // 创建Runnable和Thread对象
        Runnable r1 = new MyRunnable();
        Thread t1 = new Thread(r1);

        // 调用两次start方法
        t1.start();
        t1.start();

    }
}

/**
 * 实现Runnable方式,创建线程
 */
class MyRunnable implements Runnable{

    public void run() {
        System.out.println("两次调用start方法启动线程");
    }
}

4.直接调用run方法

package com.anan.thread.startthread;

/**
 * 直接调用run方法启动线程
 */
public class RunMethodDemo {

    public static void main(String[] args) {
        // 创建Runnable和Thread对象
        Runnable r1 = new MyRunnable2();
        Thread t1 = new Thread(r1);

        // 调用run方法
        t1.run();

    }
}

/**
 * 实现Runnable方式,创建线程
 */
class MyRunnable2 implements Runnable{

    public void run() {
        System.out.println("调用run方法启动线程,当前线程:"+Thread.currentThread().getName());
    }
}

5.线程启动流程分析

5.1.方法源码分析:start

/**
     * 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()
     *
     *注释:启动线程start方法源码,启动线程的流程是:
     *    第一:判断当前线程状态
     *    第二:将当前线程加入线程组
     *    第三:调用本地方法start0(),启动新线程
     */
    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".
         */
        // 第一:判断当前线程状态,如果不是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.add(this);

        boolean started = false;
        try {
            // 第三:调用本地方法start0(),启动新线程
            // 彩蛋:java编程语言的线程实现,是基于操作系统【内核】线程的方式实现
            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 */
            }
        }
    }

5.2.方法源码分析: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)
     *
     *注释:运行线程run方法源码,在方法内部:
     *    第一:调用了target对象的run方法
     *    第二:target对象是Runnable对象,相当于普通对象调用方法
     *    第三:因此不会开启新的线程,还是在主线程main中执行
     */
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

6.讨论分享

#线程启动流程:

1.在java编程语言中,正确的启动线程方式,是调用start方法

2.在start方法内部启动流程是:

  2.1.判断当前线程状态,是否是NEW状态

  2.2.如果当前线程是NEW状态,将当前线程加入线程组

  2.3.调用本地方法start0(),开启线程

#考考你答案:

1.可以调用两次start方法吗?

答案:不能,因为线程只有在NEW状态下,可以启动

2.可以调用run方法,启动线程吗?

答案:不能,因为直接调用run方法,相当于在主线程main下调用普通方法,并没有开启新的线程

原文地址:https://www.cnblogs.com/itall/p/12258418.html

时间: 2024-08-27 20:55:41

线程八大基础核心二(启动线程)的相关文章

线程八大基础核心六(线程属性)

1.引子 在java多线程并发编程中,有八大基础核心.考考你: 看看都有哪八大基础核心呢?它们分别是: 1.创建线程的方式 2.线程启动 3.线程停止 4.线程生命周期 5.线程相关的方法 6.线程相关的属性 7.线程异常处理 8.线程安全 今天我们从第六个基础核心开始:线程相关属性 2.考考你 #前情回顾 在我们日常多线程编程中,需要关心线程的线程优先级有: 线程Id 线程名称 是否是守护线程 线程优先级 #考考你 1.你知道线程Id的作用吗? 2.你知道线程名称的作用吗? 3.你知道什么是守

线程八大基础核心四(线程生命周期)

1.引子 在java多线程并发编程中,有八大基础核心.考考你:看看都有哪八大基础核心呢?它们分别是: 1.创建线程的方式 2.线程启动 3.线程停止 4.线程生命周期 5.线程相关的方法 6.线程相关的属性 7.线程异常处理 8.线程安全 今天我们从第四个基础核心开始:线程生命周期 2.考考你 #前情回顾: 在java编程语言中,从线程创建,到线程执行结束,会经过一系列状态的转化,称为线程的生命周期 #考考你: 1.你知道线程生命周期中有哪些状态吗? 2.你知道各种状态对应的含义吗? 3.一图胜

线程八大基础核心五(线程相关方法一)

1.引子 在java多线程并发编程中,有八大基础核心.考考你:看看都有哪八大基础核心呢?它们分别是: 1.创建线程的方式 2.线程启动 3.线程停止 4.线程生命周期 5.线程相关的方法 6.线程相关的属性 7.线程异常处理 8.线程安全 今天我们从第五个基础核心开始:线程相关方法 2.考考你 #前情回顾1.在java编程语言中,与线程相关的方法主要有: 1.1.Object.wait/Object.notify/Object/notifyAll 1.2.Thread.sleep/Thread.

线程八大基础核心一(创建线程的方式)

1.引子 在java多线程并发编程中,有八大基础核心.考考你:看看都有哪八大基础核心呢?它们分别是: 1.创建线程的方式 2.线程启动 3.线程停止 4.线程生命周期 5.线程相关的方法 6.线程相关的属性 7.线程异常处理 8.线程安全 今天我们从第一个基础核心开始:创建线程的方式 2.考考你 #考考你: 你知道在java编程语言中,有几种创建线程的方式吗? #参考如下:网友说法.官方文档 网友说法: 官方文档说法: #说法比较: 在网络上,关于创建线程的方式.主流的说法有四种:继承Threa

Java线程学习笔记(二) 线程的异常捕捉

线程异常的捕捉: 正常的情况下,我们在main()方法里是捕捉不到线程的异常的,例如以下代码: public class ExceptionThread implements Runnable{ @Override public void run() { throw new NullPointerException(); } public static void main(String[] args) { ExecutorService executorService = Executors.n

多线程学习-基础(二)线程状态装换

一.线程状态转换 下面的这个图非常重要!你如果看懂了这个图,那么对于多线程的理解将会更加深刻 状态说明:(1)新建状态(New):新创建了一个线程对象.(2)就绪状态(Runnable):线程被创建后,其他线程调用了该对象的start()方法.该状态的线程位于可运行的线程池中,变得可运行,等待获取cpu的使用权限.(3)运行状态(Running):就绪状态的线程获取了cpu的使用权,执行程序代码.(4)阻塞状态(Blocked):阻塞状态是线程由于某种原因放弃了cpu的使用权,暂时停止运行,直到

线程学习--(十二)线程池

一.Executor框架 为了更好的控制多线程,jdk提供了一套线程框架Executor,帮助开发人员有效地进行线程控制.他们都在java.util.concurrent包中,是jdk并发包的核心.其中有一个比较重要的类:Executors,他扮演者线程工厂的角色,我们通过Executors创建特定功能的线程池. Executors创建线程池方法: newFixedThreadPool()方法,该方法返回一个固定数量的线程池,该方法的线程数始终不变,当有一个任务提交时,若线程池中空闲,则立即执行

线程同步机制(二)-- 线程同步辅助类

我们在线程同步机制(一)--Synchronized和Lock简要介绍中学习了同步和临界区的概念,并且讨论了多个并发任务共享一个资源时的同步情况.访问共享资源的代码块叫临界区. 我们在线程同步机制(一)--Synchronized和Lock简要介绍中学习了一下内容: synchronized关键字 Lock接口及其实现类,如ReentrantLock,ReentrantReadWriteLock.ReadLock和ReentrantReadWriteLock.WriteLock 本章我们将学习如

线程池基础篇

一.什么是线程池?为什么要用线程池? 1. 降低资源的消耗.降低线程创建和销毁的资源消耗: 2. 提高响应速度:线程的创建时间为T1,执行时间T2,销毁时间T3,免去T1和T3的时间 3. 提高线程的可管理性. 二.线程池的创建 ThreadPoolExecutor,jdk所有线程池实现的父类 三.参数介绍 先看构造函数: /** * Creates a new {@code ThreadPoolExecutor} with the given initial * parameters. * *