java线程 Runnable方式

售票系统:Runnable接口(此处票数不是静态staic)

创建一个类  并实现其Runnable接口

eg:

class Test implements Runnable {

         private int tick = 100;

          public  void run(){

            while(true){

                      if(tick>0){

                             System.out.println(Thread.currentThread().getName()+"......sale:"+tick--);

                        }

                 }

             }

}

class TicketDemo {

public Static void main (String[] args ){

Ticket t=new Ticket();

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();

}

}

步骤如下:1.定义类实现Runnable接口

2.覆盖Runnable接口中的run方法(将线程要运行的代码存放在run方法)

3.通过Thread类建立线程对象

4.将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数

(因为自定义的run方法所属的对象是Runnable接口的子类对象,所以要让线程去指定对象的run方法 ,就必须明确改run方法所属的对象)

5.调用Thread类的start方法开启线程并调用Runnable接口子类的run方法

和继承Thread的实现多线程的区别如下:

1.避免了单继承的局限性(在定义线程是建议使用Runnable接口实现)

2.存储位置不同(继承方式:线程代码存放Thread子类的方法中

实现Runnable 线程代码存放在接口的子类的run方法中

猜你喜欢

转载自blog.csdn.net/lxw23333/article/details/81285052