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;
}
}
}
}
运行结果: