多线程实现方式

线程的生命周期有如下阶段:

(1)新建状态(new)

(2)运行状态(run)

 (3)阻塞状态(block)

(4)死亡状态(dead)

在实际实现线程时,java语言提供了3种实现方式:

继承Thread类

实现Runnable接口

使用Time和TimeTask

继承thread类

package thread;
/**功能:同时执行两个流程:main流程和自定义run方法流程。
*换句话来说就是,该程序在执行两个线程,系统线程和自定义的线程。
*/
public class FirstThread extends Thread{
 public static void main(String[] args){
  //初始化线程
  FirstThread ft = new FirstThread();
  //启动线程
  ft.start();
  try{
   for(int i = 0;i<10;i++){
    //延时一秒
    Thread.sleep(1000);
    System.out.println("main"+i);
   }
  }catch(Exception e){
   
  }
 }
 public void run(){
  try{
   for(int i = 0;i<10;i++){
    Thread.sleep(1000);
    System.out.println("run"+i);
   }
  }catch(Exception e){
   
  }
 }

}

实现runnable接口

public class MyRunnableTest {
 public static void main(String[] args){
  MyRunnable mr = new MyRunnable();
  Thread t = new Thread(mr);
  t.start();
  try{
   for(int i = 0;i<10;i++){
    Thread.sleep(1000);
    System.out.println("main"+i);
   }
  }catch(Exception e){
   
  }
  
 }

}

 


public class MyRunnable implements Runnable{
 public void run(){
  try{
  for(int i = 0;i<10;i++){
   Thread.sleep(1000);
   System.out.println("run"+i);
  }
 }catch(Exception e){
  
 }

}
}

posted on 2012-05-02 22:53  belingzhong  阅读(1016)  评论(0编辑  收藏  举报

导航