//编写程序,在主线程中,循环输出“主线程执行”;
//在一条新线程中,循环输出“子线程执行”,当主线程运行结束后,字线程也要随之结束
public class Test_04 {
public static void main(String[] args) {
myThread my = new myThread();
my.setDaemon(true);
my.start();
int count = 1;
while (true) {
try {
if (count < 10) {
Thread.sleep(300);
System.out.println("主线程执行第" + (count++) + "次");
} else {
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class myThread extends Thread {
int count = 1;
public void run() {
while (true) {
try {
Thread.sleep(500);
System.out.println("子程序执行" + (count++) + "次");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |
|