//继承Thread开发线程(2种方法)
package com.test5;
public class Demo_5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Cat cat=new Cat();
cat.start();//导致run函数的运行
//与上不同,不可直接dog.satart
Dog dog=new Dog();
Thread t=new Thread(dog);
t.start();
}
}
//方法一
class Cat extends Thread{
int time=0;
//重写run函数
public void run(){
while(true){
try {
Thread.sleep(1000); //休眠1000ms,导致阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
time++;
System.out.println("hello");
if(time==10)
break; //10次后跳出while,死亡
}
}
}
//第二种方法
class Dog implements Runnable{
public void run(){ //重写run函数
while(true){
try {
Thread.sleep(1000); //每隔1s一次
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("我也可以");
}
}
}