线程学习(2)

来源:互联网 发布:浪潮软件新闻 编辑:程序博客网 时间:2024/05/29 09:08
/*
 * 线程的学习(面试重点)
 * 创建线程的第二种方式:   实现Runnable 接口
 * 步骤:
 * 1.定义类实现Runnable接口
 * 2.覆盖Runnable接口中的run方法;
 * 将线程要运行的代码存放在该run方法中。
 * 3.通过Thread 类建立线程对象
 * 4.将Runable接口的子类对象作为实际参数传递给Thread类的构造函数;
 * 为什么要将Runnable接口的子类对象传递给Thread的构造函数。
 * 因为,自定义的run方法所属的对象时Runnable接口的子类对象。
 * 所以,要让线程去实现指定对象的run方法,就必须明确该run方法的所属对象。
 * 
 * 5.调用Thread 类的Start方法开启线程并调用Runnable接口子类的run方法;
 
 *实现方法和继承方式的区别(面试重点)
 *实现可以进行多实现,而避免了单继承的局限性;
 *在定义线程时,建议使用实现方式。
 *两种方式的区别:
 *继承Thread:  线程代码存放Thread子类run方法中。
 *实现Runnable。线程代码存放在接口的子类的run方法中。
 *
 *
 */


class SellTicket   implements  Runnable{
private  int ticket=100;


@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if (ticket>0){
System.out.println(Thread.currentThread().getName()+"卖了一张票---->还剩下"+ticket--+"张票");
//ticket--;
}
}
}

}




public class Test1{
public static void main(String []args){

SellTicket  ticket=new SellTicket();
Thread  t1=new Thread(ticket);
Thread  t2=new Thread(ticket);
Thread  t3=new Thread(ticket);
t1.start();
t2.start();
t3.start();

}
}
0 0
原创粉丝点击