//创建Thread类的子类来创建线程
class MyThread extends Thread // 继承Thread类
{
private String who;
public MyThread(String str) // 构造方法
{
who = str;
}
public void run() // 必须覆盖父类Thread里的run()方法!!!
{
for (int i = 0; i < 5; i++) {
try {
// sleep 0~1s sleep单位ms
sleep((int) (1000 * Math.random())); // sleep()方法必须写在try-catch块内
// 因为sleep()会抛出InterruptedException类型的异常
} catch (InterruptedException e) {
}
System.out.println(who + "正在运行!");
}
}
}
public class App11_1 {
public static void main(String[] args) {
MyThread you = new MyThread("你");
MyThread she = new MyThread("她");
you.start(); // start()激活! 而不是run()
she.start(); // 2个线程几乎同时激活,谁先运行看谁睡得时间短 2*5=10
System.out.println("主方法main()运行结束!"); // 看谁先抢到CPU资源,通常先运行,因为它不用经过线程激活的过程
}
}
App11_01_创建Thread类的子类来创建线程
最新推荐文章于 2021-10-25 21:59:26 发布