创建线程继承Thread和实现Runnable接口

创建线程继承Thread和实现Runnable接口

继承Thread类

在java中如何创建线程:
1、继承Thread类;
线程类:只有Thread类或者Thread类的子类


1.写个类A继承java。lang。Thread类
2.在类A中重写Thread中的run()方法
3.在run()中写需要执行的操作,run()里面的代码---线程执行体
4.在main方法中,启动线程--创建线程对象,调用start()方法。
A a=new ();
a.start();

不是调用run(),如果调run,好比是对象调方法,
程序中还是只有一条主线程。

下面是例子:

package com.briup.day18;

/*
 * 50个苹果,找三位同学,将Student类定义成线程(把每一位同学当做是一条线程)
 */

public class AppleDemo1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Student s1 = new Student("A");
        Student s2 = new Student("B");//由于下面只有有参构造器,所以这里必须要有具体的名字,这的A是线程的名字,另外注意和实现Runnable时起名字是不同的
        Student s3 = new Student("C");
        s1.start();
        s2.start();
        s3.start();


    } 

}

class Student extends Thread{

    private int count = 50;

    public Student(String name){
        super(name);
    }
    @Override
    public void run(){

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

            System.out.println(getName()+"吃苹果" +count--);

        }

    }
}

2、实现Runnable接口:

1.写个类A实现Runnable接口;类A不是线程类。
2.覆盖接口中的run方法
3.在run()中写需要执行的操作,run()里面的代码---线程执行体
4.在main方法中,启动线程--创建线程对象,调用start()方法。
       创建线程类对象:
       Thread thread=new Thread(new A());
       启动线程:
        thread.start();//一定是线程调用方法
      可以分开写:
      A a = new A();
      Thread thread = new Thread(a);
      thread.start();
package com.briup.day18;

public class AppleDemo2 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Apple a =new Apple();

        Thread thread1 = new Thread(a,"A");//注意这里给线程起名字
        Thread thread2 = new Thread(a,"B");
        Thread thread3 = new Thread(a,"C");

        thread1.start();
        thread2.start();
        thread3.start();



    }

}

class Apple implements Runnable{

    private int appleCount = 50;

    public void run(){


    for(int i=0;i<50;i++){
        if(appleCount>0){
        //获得线程的名字同样需要线程来调度
        System.out.println(Thread.currentThread().getName()+"吃苹果    "+appleCount--); 

        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    }

}

3 、通过匿名内部类实现
在某一个对象只是用一次的时候会出现

匿名内部类创建线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值