实现线程的两个方法

来源:互联网 发布:mac版搜狗五笔造词 编辑:程序博客网 时间:2024/05/01 09:23

1、继承Thread类

class Ticket extends Thread {private static int tick = 100;public void run() {while (true) {System.out.println(Thread.currentThread().getName() + "sale:"+ tick--);if (tick < 0)break;}}}public class TicketDemo {public static void main(String[] args) {  Ticket t1=new Ticket();   Ticket t2=new Ticket();   Ticket t3=new Ticket();   t1.start();   t2.start();   t3.start(); }}

2、实现Runnable接口

class TicketRun implements Runnable {private int tick = 100;@Overridepublic void run() {while (true) {System.out.println(Thread.currentThread().getName() + "sale:"+ tick--);if (tick < 0)break;}}}public class TicketDemo {public static void main(String[] args) { TicketRun tr = new TicketRun();new Thread(tr).start();new Thread(tr).start();new Thread(tr).start();}}


 

以上的方法 一把都是通过实现Runnable接口 因为在java中类是单继承的 但是接口不同 。
原创粉丝点击