线程的创建


1、继承Thread类

子类覆写父类中的run方法,将线程运行的代码存放在run中。

建立子类对象的同时线程也被创建。

通过调用start方法开启线程。

2、实现Runnable接口

子类覆盖接口中的run方法。

通过Thread类创建线程,并将实现了Runnable接口的子类对象作为参数传递给Thread类的构造函数。

Thread类对象调用start方法开启线程。

可使用匿名内部类来写

package july7;  //线程的两种方法

class MyThread extends Thread{

    private String name;

    public MyThread(String name) {    super();     this.name = name; }

    public void run(){System.out.println(name+"启动!"); }

}

 

class YourThread implements Runnable{

    private String name;

    public YourThread(String name) {      this.name = name; }

    public void run() {

       for (int i = 0; i < 3; i++) {

           System.out.println(Thread.currentThread().getName()+"第"+i+"次启动!"); }}}

 

public class Demo1 {

    public static void main(String[] args) {

       for (int i = 0; i < 100; i++) {

           if(i == 50){

              new MyThread("li").start();

              new Thread(new YourThread(""),"xiatian").start();

           }

       }

    }

}

 

Thread类中run()start()方法的区别如下:
run()
方法:在本线程内调用该Runnable对象的run()方法,可以重复多次调用;
start()
方法:启动一个线程,调用该Runnable对象的run()方法,不能多次启动一个线程;

 两种进程创建方式比较

A extends Thread:(简单)  、不能再继承其他类了(Java单继承)、同份资源不共享

A implementsRunnable:(推荐) 、多个线程共享一个目标资源,适合多线程处理同一份资源。

该类还可以继承其他类,也可以实现其他接口。

 

package july7;

//线程卖票的例子

 

class SellTicket extends Thread{

    private String name;

    private int num = 50;

    public SellTicket(String name) {

       super();

       this.name = name;

    }

   

    public void run(){

       for (int i = 1; i <=num; i++) {

           System.out.println(name+"卖出了第"+i+"张票!");

       }

    }

}

 

class MySell implements Runnable{

    private int num = 50;

   

    @Override

    public void run() {

       for (int i = 1; i <=num; i++) {

           System.out.println(Thread.currentThread().getName()+"卖出了第"+i+"张票!");

       }

    }

}

 

public class Demo2 {

    public static void main(String[] args)throws Exception {

      

       new SellTicket("A").start();

       new SellTicket("B").start();

       new SellTicket("C").start();

      

       new Thread(new MySell(),"D").start();

       new Thread(new MySell(),"E").start();

       new Thread(new MySell(),"F").start();

      

       for (int i = 10; i > 0; i--) {

           System.out.println(i);

           Thread.sleep(1000);

       }

    }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值