目录
0. 碎碎念,实现方法
1. Cat线程类
2. 测试main方法
3. 测试结果
0. 碎碎念,实现方法
0.1. 继承Thread类, 重写run方法。
0.2. 继承Runable类,重写run方法。
0.1. 继承Thread类, 重写run方法。
0.2. 继承Runable类,重写run方法。
Thread结构图
1.当一个类继承了Thread, 该类就可以当作一个线程使用 2.重写run方法,加上自己的业务逻辑 3.thread类实现Runable接口的方法
1. Cat线程类
public class Cat extends Thread {
//当一个类继承了Thread, 该类就可以当作一个线程使用
@Override
public void run() {
int times = 0;
while (true){
//每隔一秒在控制台输出小猫
System.out.println("hello,我是小猫猫" + (++times));
//让该线程休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times==20){ //当线程执行到20次时候,结束循环。
break;
}
}
}
}
2. 测试main方法
public class Thread01 {
public static void main(String[] args) {
//创建cat, 可以当作线程使用
Cat cat = new Cat();
//启动线程
cat.start();
}
}
3. 测试结果
hello,我是小猫猫1
hello,我是小猫猫2
hello,我是小猫猫3
hello,我是小猫猫4
hello,我是小猫猫5
hello,我是小猫猫6
hello,我是小猫猫7
hello,我是小猫猫8
hello,我是小猫猫9
hello,我是小猫猫10
hello,我是小猫猫11
hello,我是小猫猫12
hello,我是小猫猫13
hello,我是小猫猫14
hello,我是小猫猫15
hello,我是小猫猫16
hello,我是小猫猫17
hello,我是小猫猫18
hello,我是小猫猫19
hello,我是小猫猫20
public class Thread01 {
public static void main(String[] args) {
//创建cat, 可以当作线程使用
Cat cat = new Cat();
//启动线程
cat.start();
}
}
3. 测试结果
hello,我是小猫猫1
hello,我是小猫猫2
hello,我是小猫猫3
hello,我是小猫猫4
hello,我是小猫猫5
hello,我是小猫猫6
hello,我是小猫猫7
hello,我是小猫猫8
hello,我是小猫猫9
hello,我是小猫猫10
hello,我是小猫猫11
hello,我是小猫猫12
hello,我是小猫猫13
hello,我是小猫猫14
hello,我是小猫猫15
hello,我是小猫猫16
hello,我是小猫猫17
hello,我是小猫猫18
hello,我是小猫猫19
hello,我是小猫猫20
hello,我是小猫猫1
hello,我是小猫猫2
hello,我是小猫猫3
hello,我是小猫猫4
hello,我是小猫猫5
hello,我是小猫猫6
hello,我是小猫猫7
hello,我是小猫猫8
hello,我是小猫猫9
hello,我是小猫猫10
hello,我是小猫猫11
hello,我是小猫猫12
hello,我是小猫猫13
hello,我是小猫猫14
hello,我是小猫猫15
hello,我是小猫猫16
hello,我是小猫猫17
hello,我是小猫猫18
hello,我是小猫猫19
hello,我是小猫猫20



