测试代码
public class Thread01 {
public static void main(String[] args) throws InterruptedException {
//创建Cat对象,可以当做线程使用
Cat cat = new Cat();
cat.start();//启动一个子线程 Thread-0 -> 最终会执行cat的run方法
//说明:当main线程启动一个子线程 Thread-0,主线程不会阻塞,会继续执行
System.out.println("主线程继续执行" + Thread.currentThread().getName());
for (int i = 0; i < 60; i++) {
System.out.println("主线程 i=" + i);
//让主线程休眠
Thread.sleep(1000);
}
}
}
class Cat extends Thread {
int times = 0; //记录输出的次数
@Override
public void run() {//重写run方法,写上自己的业务逻辑
while (true) {
//该线程每隔1秒。在控制台输出 “喵喵, 我是小猫咪”
System.out.println("喵喵, 我是小猫咪" + (++times) + " 线程名=" + Thread.currentThread().getName());
//让该线程休眠1秒
try {
Thread.sleep(1000); //毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times == 80) {
break;//当times 到 80, 退出while, 这时线程也就退出..
}
}
}
}
JConsole操作流程