Java线程

2024-06-28 08:47

Java线程

Java线程中自,类需要实现Runnable接口

import org.junit.Test;

public class TestJuc1 {

    @Test
    public void test1() throws InterruptedException {
        Thread t1 = new Thread(new Runnable() {
            @Override
             public void run() {
                    System.out.println("hello world");
                }
        });
        t1.start();
     
    }
}

如下图java线程Thread的实例化(初始化代码)

image.png

Thread的构造函数调用初始化方法init()

init初始化方法负责初始化thread对象相关参数

 private void init(ThreadGroup g, Runnable target, String name,
                      long stackSize, AccessControlContext acc,
                      boolean inheritThreadLocals) {
        if (name == null) {
            throw new NullPointerException("name cannot be null");
        }

        this.name = name;

        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 (inheritThreadLocals && 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();
    }

该init方法实现实例化线程Thread的参数

而Thread.start()

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.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 */
            }
        }
    }

启用线程的方法它调用了

/**
     * 本机方法,负责实际启动当前线程。
     * <p>
     * 该方法被声明为私有native,意味着它是一个与平台相关的本机方法,具体实现位于JVM中。
     * 它的目的是开始当前线程的执行,这是线程生命周期中的第一步。
     * 由于该方法的实现依赖于特定的平台(例如,Windows或Linux上的线程启动机制不同),
     * 因此它被声明为native,其具体实现由JVM提供。
     * <p>
     * 方法名中的"0"后缀是一种常见的命名惯例,用于表示本机方法,它没有实际的语义含义。
     * 它的使用是为了与Java的JNI(Java Native Interface)机制保持一致,该机制要求本机方法具有特定的命名模式。
     * <p>
     * 注意:该方法没有参数和返回值,因为它的目的只是启动线程,不需要传递任何信息或期望获得任何结果。
     */
    private native void start0();


 /**
     * 当线程被激活时,此方法将被执行。该方法的目的是执行特定的任务或操作。
     * 本方法的实现决定了线程的具体行为。
     */
    public void run() {
        // 在这里编写执行线程任务的代码
    }

Java中的Thread类提供了丰富的API来创建、管理和控制线程。以下是一些常用方法及其用途:

  1. start():

    • 用途: 启动线程并执行其run()方法。调用此方法后,线程进入可运行状态(Runnable)。

  2. run():

    • 用途: 定义线程要执行的任务。通常需要重写此方法以包含自定义的逻辑。

  3. currentThread()(静态方法):

    • 用途: 返回当前正在执行的线程对象的引用,常用于获取当前线程的信息。

  4. getName() 和 setName(String name):

    • 用途: 分别用于获取和设置线程的名称,有助于调试和监控。

  5. join():

    • 用途: 当前线程等待调用此方法的线程结束。可以带参数指定等待时间。

  6. sleep(long millis):

    • 用途: 强制当前正在执行的线程暂停执行指定的毫秒数,使线程进入限时等待状态。

  7. yield():

    • 用途: 让出CPU执行权,使当前线程从运行状态变为可运行状态,让其他相同优先级的线程有机会执行。但这不是一个强制性的操作,实际行为依赖于操作系统的线程调度策略。

  8. isAlive():

    • 用途: 判断线程是否还在执行,即是否已启动且尚未死亡。

  9. interrupt():

    • 用途: 中断线程。设置线程的中断标志位,通常用于取消线程的阻塞状态,如从wait(), join(), 或 sleep()方法中提前返回。

  10. isInterrupted():

    • 用途: 测试线程是否被中断,不改变中断状态。

  11. interrupted() (静态方法):

    • 用途: 测试当前线程是否被中断,并清除中断状态。

  12. getState():

    • 用途: 获取线程当前的状态,返回的是Thread.State枚举值。

  13. setPriority(int newPriority):

    • 用途: 设置线程的优先级,范围在MIN_PRIORITY(1)到MAX_PRIORITY(10)之间,默认为NORM_PRIORITY(5)。

  14. getPriority():

    • 用途: 获取线程的优先级。

  15. wait(),wait(long timeout),wait(long timeout, int nanos):

    • 用途: 使当前线程等待,直到另一个线程调用此对象的**notify()notifyAll()**方法,或者超过指定的等待时间。这些方法必须在同步上下文中使用。

  16. notify() 和notifyAll():

    • 用途: 唤醒在此对象监视器上等待的一个或所有线程。同样,这些方法应在同步代码块或方法中调用。

它的流程

image.png

相关新闻
热点
视频
投票
查看结果
Tags

站点地图 在线访客: 今日访问量: 昨日访问量: 总访问量:

© 2025 个人网站 版权所有

备案号:苏ICP备2024108837号

苏公网安备32011302322151号