Fork me on GitHub

thread跟Runnable实现多线程

 1 //两种实现方式的区别和联系:
 2 //在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类有如下好处:
 3 //避免点继承的局限,一个类可以继承多个接口。
 4 //适合于资源的共享  10张票没有资源共享
 5 public class TicketThreadImpl implements Runnable {
 6     private int ticket=10;
 7     public void run(){
 8         for(int i=1;i<=20;i++){
 9             if(ticket>0)
10             System.out.println("线程开始:"+ticket--);            
11         }    
12     }
13     public static  void main(String args[]){
14         TicketThreadImpl m1=new TicketThreadImpl();
15         //TicketThreadImpl m2=new TicketThreadImpl();
16         //TicketThreadImpl m3=new TicketThreadImpl();
17         new Thread(m1).start();//同一个mt,但是在Thread中就不可以,如果用同一
18         new Thread(m1).start();//个实例化对象mt,就会出现异常  
19         new Thread(m1).start();
20     }
21 
22 }
 1 //继承Thread方式
 2 public class TicketThread extends Thread{
 3     private int ticket=10;
 4     public void run(){
 5         for(int i=1;i<=10;i++)
 6         {
 7             if(ticket>0)
 8             System.out.println("线程开始:"+ticket--);            
 9         }
10     }
11     public static void main(String args[])
12     {
13         TicketThread m1=new TicketThread();//每个线程都各卖了10张,共卖了30张票  
14         TicketThread m2=new TicketThread();//但实际只有10张票,每个线程都卖自己的票  
15         TicketThread m3=new TicketThread();//没有达到资源共享  
16         m1.start();
17         m2.start();
18         m3.start();
19         
20     }
21     
22 
23 }

 

posted @ 2015-11-03 21:40  ZZZZW  阅读(230)  评论(0编辑  收藏  举报
AmazingCounters.com