多线程(一)

一、         java多线程

在java中实现多线程可以有两种方法(推荐使用第二种方法):

1、              继承Thread类:

class ThreadTest extends Thread{

   public ThreadTest(String name){

     super(name);

   }

   public void run(){

     for(int i=0;i<50000;i++){

        System.out.println(this.getName()+"::"+i);

     }

   }

}

public class ThreadDemo2 {

   public static void main(String[] args) {

     // TODO Auto-generated method stub

     ThreadTest t1=new ThreadTest("A");

     ThreadTest t2=new ThreadTest("B");

     t1.start();

     t2.start();

   }

 

}

 

2、              继承Runnable接口:

class RunDemo implements Runnable{

   private String name;

   public RunDemo(String name){

     this.name=name;

   }

   @Override

   public void run() {

     for(int i=0;i<5000;i++){

        System.out.println(this.name+"::"+i);

     }

   }  

}

public class ThreadDemo {

   public static void main(String args[]){

     RunDemo run1=new RunDemo("A");

     RunDemo run2=new RunDemo("B");

     Thread t1=new Thread(run1);

     Thread t2=new Thread(run2);

     t1.start();

     t2.start();

   }

}

 

无论是第一种方法还是第二种方法,他们都必须重写run方法,多线程操作将在run方法中进行。

posted @ 2011-08-10 11:37  rorshach  阅读(105)  评论(0编辑  收藏  举报