java - 线程运行如何开始?

标签 java multithreading

我在看一个关于线程的小例子。为了创建线程,我们可以通过实现 Runnable 接口(interface)或扩展 Thread 来实现两种方式。我使用了第一种方式

package test;

public class test implements Runnable{
    public static void main(String args[])
    {
        test t=new test();
        t.run();Thread th=Thread.currentThread();
        th.start();
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println("hi");
    }
}

我的疑问是当我们调用 th.start(); 然后 run() 被调用。我想知道如何。我在内部认为 start() 可能正在调用 run() 所以我查看了 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 */
        }
    }
}

正如您在 start() 中看到的,run() 没有被调用,但是当我们调用 th.start() 时自动覆盖 run() 被调用。任何人都可以对此有所了解

最佳答案

在新线程上调用 run 方法的机制是语言之外的:它不能用 Java 代码表示。这是 start 方法中的关键行:

    start0();

start0 是一个本地方法,其调用将:

  • 创建一个新的本地执行线程;
  • 导致在该线程上调用 run 方法。

关于java - 线程运行如何开始?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22012067/

相关文章:

java - join() 方法和《完整 Java 引用》第 9 版

java - 如何在 Java 中将 ImageInputStream 转换为 BufferedImage?

Java , tdd 方法, IO 操作

multithreading - InfiniBand:传输速率取决于MPI_Test *频率

multithreading - 新线程,应用程序在阶段关闭后仍在运行

java - SWT 中的 'show' 和 'paint' 事件有什么区别?

Ruby rake 任务线程优化

java - 启动和停止线程-JButton 对齐

java - Android日常工作凌晨12点

java - 安卓工作室;底部导航 View = 空