匿名内部类创建线程:(简单的需求在使用)
Runnable run=new Runnable(){//即创建了Runnable的子类又创建了该子类的对象
public void run(){
//线程要执行的代码
}
};
new Thread(run).start();
a.继承Thread类:Java只支持继承一旦Demo_02SubThread继承其它类,就无法在继承Thread类
这种方式不推荐使用
public class Demo_02SubThread extends Thread{
private static int tickets = 100;
public void run(){
System.out.println(this.getName()+"继承方式,实现线程");
}
}
public static void main(String[] args) {
//创建Thread子类对象
Demo_02SubThread sub = new Demo_02SubThread();
Demo_02SubThread sub2 = new Demo_02SubThread();
Demo_02SubThread sub3 = new Demo_02SubThread();
//子类对象,调用父类方法start
sub.start();
}
匿名内部类创建线程:(简单的需求在使用):
new Thread(){//即创建了Thread的子类又创建了该子类的对象
public void run(){
//线程要执行的代码
}
}.start();