Runnable 接口

在程序开发中只要是多线程肯定永远以实现Runnable接口为主,因为实现Runnable接口相比继承Thread类有如下好处:

避免点继承的局限,一个类可以继承多个接口。
•适合于资源的共享

  • 以卖票程序为例,通过Thread类完成:
class MyThread extends Thread{  
	private int ticket=10;  
	public void run(){  
		for(int i=0;i<20;i++){  
			if(this.ticket>0){  
				System.out.println("卖票:ticket"+this.ticket--);  
			}  
		}  
	}  
};

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

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

  • 如果用Runnable就可以实现资源共享,下面看例子:
package org.demo.runnable; 
class MyThread implements Runnable{ 
	private int ticket=10; 
	public void run(){ 
		for(int i=0;i<20;i++){ 
			if(this.ticket>0){ 
				System.out.println("卖票:ticket"+this.ticket--); 
			} 
		} 
	} 
} 
package org.demo.runnable; 
public class RunnableTicket { 
	public static void main(String[] args) { 
		MyThread mt=new MyThread(); 
		new Thread(mt).start();//同一个mt,但是在Thread中就不可以,如果用同一 
		new Thread(mt).start();//个实例化对象mt,就会出现异常 
		new Thread(mt).start(); 
	} 
}; 
虽然现在程序中有三个线程,但是一共卖了10张票,也就是说使用Runnable实现多线程可以达到资源共享目的


评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿姨不可以嘛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值