目录
0. 碎碎念,实现方法
0.1. 继承Thread类, 重写run方法。
0.2. 继承Runable类,重写run方法。
Thread结构图
1.当一个类继承了Thread, 该类就可以当作一个线程使用
2.重写run方法,加上自己的业务逻辑
3.thread类实现Runable接口的方法
1. Cat线程类
package com.edu.threaduse;
/**
* @author 大力pig
*/
/**
* 1.当一个类继承了Thread, 该类就可以当作一个线程使用
* 2.重写run方法,加上自己的业务逻辑
* 3.thread类实现Runable接口的方法
*/
public class Cat extends Thread {
//当一个类继承了Thread, 该类就可以当作一个线程使用
@Override
public void run() {
int times = 0;
while (true){
//每隔一秒在控制台输出小猫
System.out.println("hello,我是小猫猫" + (++times) + "这是线程"+Thread.currentThread());
//让该线程休眠1秒
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (times==100){ //当线程执行到100次时候,结束循环。
break;
}
}
}
}
}
2. 测试main方法
主线程和子线程一起调用实现。会有交替调用的效果。
package com.edu.threaduse;
/**
* @author 大力pig
*/
public class Thread01 {
public static void main(String[] args) {
//创建cat, 可以当作线程使用
Cat cat = new Cat();
//启动线程
cat.start();
//说明: 当main线程启动一个线程, Thread-0, 主线程不会阻塞, 会继续执行。
System.out.println("主线程继续执行" + Thread.currentThread().getName());
for (int i = 0; i < 50; i++) {
System.out.println("主线程 i = " + i);
//让主线程休眠
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
3. 测试结果