心胸决定格局,眼界决定境界...

Java中Runnable和Thread的区别

http://developer.51cto.com/art/201203/321042.htm

以卖票程序为例,通过Thread类完成:

  1. package org.demo.dff;  
  2. class MyThread extends Thread{  
  3. private int ticket=10;  
  4. public void run(){  
  5. for(int i=0;i<20;i++){  
  6. if(this.ticket>0){  
  7. System.out.println("卖票:ticket"+this.ticket--);  
  8. }  
  9. }  
  10. }  
  11. }; 

下面通过三个线程对象,同时卖票:

  1. package org.demo.dff;  
  2. public class ThreadTicket {  
  3. public static void main(String[] args) {  
  4. MyThread mt1=new MyThread();  
  5. MyThread mt2=new MyThread();  
  6. MyThread mt3=new MyThread();  
  7. mt1.start();//每个线程都各卖了10张,共卖了30张票  
  8. mt2.start();//但实际只有10张票,每个线程都卖自己的票  
  9. mt3.start();//没有达到资源共享  
  10. }  

如果用Runnable就可以实现资源共享,下面看例子:

  1. package org.demo.runnable;  
  2. class MyThread implements Runnable{  
  3. private int ticket=10;  
  4. public void run(){  
  5. for(int i=0;i<20;i++){  
  6. if(this.ticket>0){  
  7. System.out.println("卖票:ticket"+this.ticket--);  
  8. }  
  9. }  
  10. }  
  11. }  
  12. package org.demo.runnable;  
  13. public class RunnableTicket {  
  14. public static void main(String[] args) {  
  15. MyThread mt=new MyThread();  
  16. new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一  
  17. new Thread(mt).start();//个实例化对象mt,就会出现异常  
  18. new Thread(mt).start();  
  19. }  
  20. }; 

虽然现在程序中有三个线程,但是一共卖了10张票,也就是说使用Runnable实现多线程可以达到资源共享目的。

posted @ 2016-06-22 11:57  WELEN  阅读(108)  评论(0)    收藏  举报