package test;
/**
* @author 小小小白白白白
*/
public class Cpu {
public static void main(String[] args) throws InterruptedException {
Hello hello = new Hello();
Thread thread = new Thread(hello);
for(int i=0; i<10;i++){
System.out.println("主线程"+i);
//休眠一秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(i==5){
thread.start();
thread.join();
}
}
}
}
class Hello implements Runnable {
@Override
public void run() {
int amount = 0;
while (true) {
System.out.println("Hello" + (++amount));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (amount == 10) {
break;
}
}
}
}
守护线程
package test;
/**
* @author 小小小白白白白
*/
public class Cpu {
public static void main(String[] args) throws InterruptedException {
Hello hello = new Hello();
Thread thread = new Thread(hello);
//如果希望main线程结束后,子线程自动结束
//只需要将子线程设为守护线程即可
thread.setDaemon(true);
thread.start();
for(int i=0; i<10;i++){
System.out.println("主线程"+i);
Thread.sleep(1000);
}
}
}
class Hello implements Runnable {
@Override
public void run() {
int amount = 0;
while (true) {
System.out.println("Hello" + (++amount));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}