Android-Thread类的子类创建线程

Thread类的子类创建线程

优点:可以在子类中增加新的成员变量,使线程具有某种属性,
也可以在子类中新增方法,使线程具有某种能力。

在Java语言中,用Thread类或子类创建线程对象

在编写Thread类的子类中,需要重写父类的run()方法,目的是规定线程的具体操作,否则线程什么也不做, 因为父类的run()方法中没有任何操作语句

代码:
public class Demo43{

public static void main(String[] args){
    Cake cake = new Cake();
    int size = 10;
    cake.setSize(size);
    System.out.println("蛋糕大小是"+size+"克");

    Ant antRed = new Ant("红蚂蚁",cake);
    Ant antBlack = new Ant("黑蚂蚁",cake);
    antRed.start();
    antBlack.start();
}

}

public class Cake{
int size;

public void setSize(int n){
    size = n;
}
public int getSize(){
    return size;
}

public void lost(int m){
    if (size - m > 0){   
        size = size - m;

}    

}
}

public class Ant extends Thread{

Cake cake;

public Ant(String name, Cake cake){
    this.cake = cake;
    setName(name);
}

@Override
public void run(){
    while(true){
        int n = 2;
        System.out.println(getName()+"吃"+n+"克蛋糕");
        cake.lose(n);
        System.out.println(getName()+"发现蛋糕还剩下"+Cake.getSize()+"克");

        try{
           sleep(1000);
        }catch(InterruptedException e){
           e.printStackTrace();
        }

        if(cake.getSize()<=0){
           System.out.println(getName()+"已经进入死亡状态");
           return;
        }
    }
 }

}

运行结果:
在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值