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

java创建线程的第二种方式:实现Runnable接口

2013-08-01 21:49 639 查看
/*需求:简单的卖票系统、
* 多个窗口买票
*
* 创建线程的第二种方式:实现Runnable接口
*
* 步骤:
* 1、定义类实现Runnable接口
* 2、覆盖Runnable接口中的run方法
* 		将线程覆盖运行的代码存放在该run方法中。
* 3、通过Thread类建立线程对象
* 4、将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数
* 		为什么要将Runnable接口的子类对象传递给Thread的构造函数。
* 		因为,自定义的run方法所属的对象是Runnable接口的子类对象。
* 		所以要让线程去指定对象的run方法,就必须明确该run方法所属对象。
* 5、调用Thread类的start方法开启线程并调用Runnable接口子类的run方法
* 实现方式和继续方式有什么区别呢?
* 实现方式好处:避免了单继承的局限性。
* 在定义线程时,建立使用实现方式。
* 两种方式区别:
* 继承Thread:线程代码存放在Thread子类run方法中。
* 实现Runnable。线程代码存在接口的子类的run方法中。
* */
class Ticke implements Runnable {//extends Thread
private int ticke = 100;
public void run(){
while(true){
if(ticke>0){
System.out.println(Thread.currentThread().getName() + "sale : " + ticke--);
}
}
}
}
public class TicketDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Ticke t = new Ticke();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
/*	Ticke t1 = new Ticke();
Ticke t2 = new Ticke();
Ticke t3 = new Ticke();
Ticke t4 = new Ticke();
t1.start();
t2.start();
t3.start();
t4.start();*/
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐