Java线程有两种实现方式,一是直接继承Thread类,二是实现Runable接口,
先看看继承Thread类的实现, 在这里同时做了一个方法,控制Thread的运行
1 import java.lang.Thread; 2 public class ThreadA extends Thread{ 3 private boolean isThreadStart = true; 4 public void run(){ 5 int i = 0; 6 while(isThreadStart){ 7 System.out.println("ThreadA is running..." + i++); 8 } 9 } 10 public void trunOffThread(){ 11 this.isThreadStart = false; 12 } 13 }
Runable接口的实现
1 import java.lang.Runnable; 2 public class ThreadB implements Runnable{ 3 private boolean isThreadStart = true; 4 public void run(){ 5 int i = 0; 6 while(isThreadStart){ 7 System.out.println("ThreadB is running..." + i++); 8 } 9 } 10 11 synchronized public void trunOffThread(){ 12 this.isThreadStart = false; 13 } 14 15 }
两个类创建好后,建立测试类
1 /* 2 * Created by Aram 20130313 3 * Thread practise 4 **/ 5 import java.lang.Thread; 6 import java.lang.Runnable; 7 8 public class ThreadPractise1{ 9 10 11 static public void main(String[] args){ 12 ThreadA threadA = new ThreadA(); 13 threadA.start(); // start threadA; 14 ThreadB runB = new ThreadB(); // which implements Runable 15 Thread threadB = new Thread(runB); 16 threadB.start();// start threadB; 17 18 for(int i = 0; i < 200; i++){ 19 System.out.println("I am main thread!! I had runned " + i); 20 } 21 System.out.println("Now go to kill threadA"); 22 threadA.trunOffThread(); 23 System.out.println("ThreadA is over"); 24 System.out.println("Now go to kill threadB"); 25 runB.trunOffThread(); 26 System.out.println("ThreadB is over"); 27 28 } 29 30 }
测试结果
I am main thread!! I had runned 199 ThreadB is running...519 ThreadA is running...251 ThreadB is running...520 ThreadB is running...521 Now go to kill threadA ThreadB is running...522 ThreadA is running...252 ThreadB is running...523 ThreadB is running...524 ThreadB is running...525 ThreadA is over ThreadB is running...526 Now go to kill threadB ThreadB is running...527 ThreadB is over
通过测试,发现继承Runnable接口的线程运行次数最多的,由此推测该线程的实现方式优先方式最高,所以在做线程编程的时候,建议大家都是用接口的方式去实现
两种实现线程的方式都是可行的,但是实现Runnable接口的线程更加优秀,原因有以下几点:
1. 突破单一继承的限制
2. 对于不同线程的同一实现接口能够共享代码;
3. 实现不同线程的数据共享
更多的线程例子可以参照以下博客,这位博主说得很清楚的说。
http://www.cnblogs.com/rollenholt/archive/2011/08/28/2156357.html