线程Thread的两种创建方式以及区别

来源:互联网 发布:17173数据库 编辑:程序博客网 时间:2024/04/30 05:27

线程的两种创建方式:

一、继承方式

步骤:

1、定义类继承Thread类

2、覆盖Thread类中的run方法

3、建立继承Thread类的子类对象

4、调用Thread类中的start方法,调用了继承Thread类的子类对象的run方法中的代码

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


二、实现runnable接口

步骤:

1、定义类实现Runnable接口

2、覆盖runnable接口中的run方法

3、通过Thread类创建线程对象

4、将runnable中的子类对象作为实参传给thread类的构造函数

5、调用Thread中的start方法开启线程调用runnable接口中的子类run方法中的代码

class Tickets implements Runnable{private static int ticket = 100;public void run(){while(true){if(ticket>0){System.out.println(Thread.currentThread()+"sale"+ticket--);}}}}public class ThreadTicketDemo02 {public static void main(String[] args) {Tickets tic = new Tickets();Thread t1 = new Thread(tic);Thread t2 = new Thread(tic);Thread t3 = new Thread(tic);Thread t4 = new Thread(tic);t1.start();t2.start();t3.start();t4.start();}}

两种方式的区别:

1、继承方式:

线程代码存放在线程子类的run方法中

2、实现接口方式:

线程方式存放在实现runnable接口的子类的run方法中

实现接口方式的好处:

避免了java中单继承的局限性



0 0
原创粉丝点击