有两种方法,一种是继承Thread类,另一种是实现Runable接口
(1)
public class Test{
public static void main(String [] args){
MyThread mt=new MyThread();
mt.start();
}
}
class MyThread extends Thread{//继承Thread类
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
sleep(1000);//每隔1m输出
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常(非运行时异常)
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
(2)
public class Test{
public static void main(String [] args){
RunableDemo rd=new RunableDemo();
Thread t=new Thread(rd);
t.start();
}
}
class RunableDemo implements Runable{//实现Runable接口
int count=0;
public void run(){//重写run()方法
while(true){
System.out.println("MyThread is running !"+count+"times");
try{
Thread.sleep(1000);//静态方法,可以用类名直接调用
count++;
}catch(InterruptedException e){//扑捉可能产生的中断异常
System.out.println("产生中断异常");
}
if(count==10)return;
}
}
}
}