您的位置:首页 > 编程语言 > Java开发

java中二种方法实现一个线程

2011-02-24 16:44 246 查看
有两种方法,一种是继承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;
}
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐