世界を開始するには、複数のスレッドを開きます

A:スタートの比較()、実行()で

コードは示してい

public class StartThread {
    public static void main(String[] args) {
        Runnable runnable = () -> {
            System.out.println(Thread.currentThread().getName());
        };

        runnable.run();
        new Thread(runnable).start();
    }
}

業績

E:\tools\jdk1.8.0_201\bin\java.exe com.example.demo.startthread.StartThread
main
Thread-0

Process finished with exit code 0

Runnable.run main()の実行結果、スレッド0は、新しいスレッド(実行可能).start()の実行結果です。あなたはなぜ求めることができますか?、読み心配しないでください。

2:原則start()メソッドの解釈

スタート()メソッド意味

  • 新しいスレッドを開始します。自由な状況の存在下での通知JVMは、新しいスレッドを開始することです
  • 準備:まず、私は、CPU以外の他のリソースを取得していることを、レディ状態でレディ状態手段を独自に行います
 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 */
            }
        }
    }

    private native void start0();

ソースコードによって、私たちは、あなたが新しいスレッドを起動したときに、スレッドがグループ、最後の呼び出しSTART0()メソッドに参加する(理由の理由を繰り返さない実行開始()メソッドである)ラフ、start()メソッドは、最初のスレッドの状態をチェックします見ることができます。

3:原則run()メソッドの解釈

ソース

@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

この方法は、そのスレッド名がメインでプリントアウトし、これは通常のメインスレッドメインの直接呼び出しであることがわかります。

リリース7件のオリジナルの記事 ウォンの賞賛6 ビュー131

おすすめ

転載: blog.csdn.net/weixin_45319877/article/details/103963723