|NO.Z.00092|——————————|BigDataEnd|——|Java&多线程.V04|——|Java.v04|线程创建|启动方式二|

一、线程创建和启动方式
package com.yanqi.task18;

public class SubRunnableRun implements Runnable {
    @Override
    public void run() {
        // 打印1 ~ 20之间的所有整数
        for (int i = 1; i <= 20; i++) {
            System.out.println("run方法中:i = " + i); // 1 2 ... 20
        }
    }
}
二、编程代码
package com.yanqi.task18;

public class SubRunnableRunTest {

    public static void main(String[] args) {

        // 1.创建自定义类型的对象,也就是实现Runnable接口类的对象
        SubRunnableRun srr = new SubRunnableRun();
        // 2.使用该对象作为实参构造Thread类型的对象
        // 由源码可知:经过构造方法的调用之后,Thread类中的成员变量target的数值为srr。
        Thread t1 = new Thread(srr);
        // 3.使用Thread类型的对象调用start方法
        // 若使用Runnable引用构造了线程对象,调用该方法(run)时最终调用接口中的版本
        // 由run方法的源码可知:if (target != null) {
        //                         target.run();
        //                    }
        // 此时target的数值不为空这个条件成立,执行target.run()的代码,也就是srr.run()的代码
        t1.start();
        //srr.start();  Error

        // 打印1 ~ 20之间的所有整数
        for (int i = 1; i <= 20; i++) {
            System.out.println("-----------------main方法中:i = " + i); // 1 2 ... 20
        }
    }
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=50270:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task18.SubRunnableRunTest
-----------------main方法中:i = 1
-----------------main方法中:i = 2
-----------------main方法中:i = 3
-----------------main方法中:i = 4
-----------------main方法中:i = 5
-----------------main方法中:i = 6
-----------------main方法中:i = 7
-----------------main方法中:i = 8
-----------------main方法中:i = 9
-----------------main方法中:i = 10
-----------------main方法中:i = 11
-----------------main方法中:i = 12
-----------------main方法中:i = 13
-----------------main方法中:i = 14
-----------------main方法中:i = 15
-----------------main方法中:i = 16
-----------------main方法中:i = 17
-----------------main方法中:i = 18
-----------------main方法中:i = 19
-----------------main方法中:i = 20
run方法中:i = 1
run方法中:i = 2
run方法中:i = 3
run方法中:i = 4
run方法中:i = 5
run方法中:i = 6
run方法中:i = 7
run方法中:i = 8
run方法中:i = 9
run方法中:i = 10
run方法中:i = 11
run方法中:i = 12
run方法中:i = 13
run方法中:i = 14
run方法中:i = 15
run方法中:i = 16
run方法中:i = 17
run方法中:i = 18
run方法中:i = 19
run方法中:i = 20

Process finished with exit code 0

 
 
 
 
 
 
 
 
 

Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
                                                                                                                                                   ——W.S.Landor

 

 

posted on 2022-04-04 15:41  yanqi_vip  阅读(30)  评论(0)    收藏  举报

导航