在实际实现线程时,JAVA语言提供了3种实现方法:
1.继承Thread类 2.实现Runnable接口 3.使用Timer和TimerTask组合
1、/*以继承Thread类的方式实现多线程*/
Public class TestThread1 extends Thread{
Public static void main(String args[]){
//创建对象
TestThread1 tt1 = new TestTread1();
//启动线程
Tt1.start();
Try{
For(int i = 0;i<5;i++){
//延时1秒
Thread.sleep(1000);
System.out.println(“Main:” + i);
}
}catch(Exception e){}
}
Public void run(){
Try{
For(int i=0;i<5;i++){
//延时1秒
Thread.sleep(1000);
System.out.println(“Run:” + i);
}
}catch(Exception e){}
}
}
/*以继承Thread的方式实现多线程*/前半部分一样,只是后面以单独类的形式实现组织代码
Public class Thread2 extends Thread{
Public void run(){
Try{
For(int i=0;i<5;i++){
//延时1秒
Thread.sleep(1000);
System.out.println(“Run:” + i);
}
}catch(Exception e){}
}
}
使用实现Runnable接口只要将上面
Public class Thread2 extends Thread改为
Class Runnable1 implements Runnable 就可以了