- 继承Thread类实现
- 覆写run方法
- 继承Thread类的对象调用start方法启动线程。
注意:1.每个线程对象只允许启动(start)一次
Thread执行分析:
- Runnable接口实现多线程(优先考虑)
示例代码:
/**
* @Author DaWeiGuo
* @Date 2020/8/13 10:55
* @desc: 通过实现接口Runnable创建线程
*/
public class DemoTwo {
public static void main(String args[]){
House house = new House();
house.setWater(10);
Thread dog = new Thread(house);
Thread cat = new Thread(house);
dog.start();
cat.start();
}
}
class House implements Runnable{
int waterAmount;
public void setWater(int w){
this.waterAmount = w;
}
@Override
public void run() {
int m = 1;
while(true){
if(waterAmount<=0){
return;
}
waterAmount = waterAmount - m;
System.out.println("剩下"+waterAmount+"克");
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}