一、多个线程执行不同的代码
### --- 案例题目
——> 编程创建两个线程,线程一负责打印1 ~ 100之间的所有奇数,
——> 其中线程二负责打印1 ~ 100之间的所有偶数。
——> 在main方法启动上述两个线程同时执行,主线程等待两个线程终止。
二、编程代码
package com.yanqi.task18;
public class SubThread1 extends Thread {
@Override
public void run() {
// 打印1 ~ 100之间的所有奇数
for (int i = 1; i <= 100; i += 2) {
System.out.println("子线程一中: i = " + i);
}
}
}
package com.yanqi.task18;
public class SubThread2 extends Thread {
@Override
public void run() {
// 打印1 ~ 100之间的所有偶数
for (int i = 2; i <= 100; i += 2) {
System.out.println("------子线程二中: i = " + i);
}
}
}
package com.yanqi.task18;
public class SubThreadTest {
public static void main(String[] args) {
SubThread1 st1 = new SubThread1();
SubThread2 st2 = new SubThread2();
st1.start();
st2.start();
System.out.println("主线程开始等待...");
try {
st1.join();
st2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程等待结束!");
}
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=50892:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin&