您的位置:首页 > 编程语言 > Java开发

Java 实现Runnable接口 资源共享

2016-05-25 09:52 676 查看
一.先看两段代码

通过继承Thread类

class MyThread extends Thread{  
      
    private int ticket = 10;  
    private String name;  
    public MyThread(String name){  
        this.name =name;  
    }  
      
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(this.name+"卖票---->"+(this.ticket--));  
            }  
        }  
    }  
}  
public class ThreadDemo {  
  
      
    public static void main(String[] args) {  
        MyThread mt1= new MyThread("一号窗口");  
        MyThread mt2= new MyThread("二号窗口");  
        MyThread mt3= new MyThread("三号窗口");  
        mt1.start();  
        mt2.start();  
        mt3.start();  
    }  
  
}  

运行结果:

一号窗口卖票---->10  
一号窗口卖票---->9  
二号窗口卖票---->10  
一号窗口卖票---->8  
一号窗口卖票---->7  
一号窗口卖票---->6  
三号窗口卖票---->10  
一号窗口卖票---->5  
一号窗口卖票---->4  
一号窗口卖票---->3  
一号窗口卖票---->2  
一号窗口卖票---->1  
二号窗口卖票---->9  
二号窗口卖票---->8  
三号窗口卖票---->9  
三号窗口卖票---->8  
三号窗口卖票---->7  
三号窗口卖票---->6  
三号窗口卖票---->5  
三号窗口卖票---->4  
三号窗口卖票---->3  
三号窗口卖票---->2  
三号窗口卖票---->1  
二号窗口卖票---->7  
二号窗口卖票---->6  
二号窗口卖票---->5  
二号窗口卖票---->4  
二号窗口卖票---->3  
二号窗口卖票---->2  
二号窗口卖票---->1 

通过实现Runnable接口

class MyThread1 implements Runnable{  
    private int ticket =10;  
    private String name;  
    public void run(){  
        for(int i =0;i<500;i++){  
            if(this.ticket>0){  
                System.out.println(Thread.currentThread().getName()+"卖票---->"+(this.ticket--));  
            }  
        }  
    }  
}  
public class RunnableDemo {  
  
      
    public static void main(String[] args) {  
        // TODO Auto-generated method stub  
        //设计三个线程  
         MyThread1 mt = new MyThread1();  
         Thread t1 = new Thread(mt,"一号窗口");  
         Thread t2 = new Thread(mt,"二号窗口");  
         Thread t3 = new Thread(mt,"三号窗口");  
         t1.start();  
         t2.start();  
         t3.start();  
    }  
  


运行结果:

一号窗口卖票---->10  
三号窗口卖票---->9  
三号窗口卖票---->7  
三号窗口卖票---->5  
三号窗口卖票---->4  
三号窗口卖票---->3  
三号窗口卖票---->2  
三号窗口卖票---->1  
一号窗口卖票---->8  
二号窗口卖票---->6

造成上面的差异的就是,继承Runnable接口的时候,new了一个Thread1 ,然后通过三个线程来共享一个Thread1 ,这样三个进程就共享了资源int ticket =10; 

MyThread1 mt1 = new MyThread1();   
MyThread1 mt2 = new MyThread1();   
MyThread1 mt2 = new MyThread1();   
Thread t1 = new Thread(mt1,"一号窗口");    
Thread t2 = new Thread(mt2,"二号窗口");    
Thread t3 = new Thread(mt3,"三号窗口");  

这样的话, 就跟继承Thread类的结果是一样的了

总结一下,,实现Runable除了避免单继承的局限外,还有个好处就是能实现不同进程资源共享,而继承Thread没有这个功能。并不是这个特点是两者的绝对区别,继承Runable你可以选择不共享。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息