这是我学习这一知识点时,老师的教案截图(斜眼笑):
Runnable接口与目标对象:
这个现在看上去不太懂(反正我当时是这样),跟着老师敲一遍,然后代码的注释自己写,应该会好很多
开始写代码
第一步:主类
这里的house是Runnable接口的实例
package com.suhzou.dajiang1;
public class main {
public static void main(String[] args) {
House house=new House();
house.setCake(10);
Thread antRed = new Thread(house);//house是Runnable的实例
antRed.setName("红蚂蚁");
Thread antBlack = new Thread(house);
antBlack.setName("黑蚂蚁");
antRed.start();
antBlack.start();
}
}
第二步:实现用Runnable接口实现多线程
package com.suhzou.dajiang1;
public class House implements Runnable{
int cake;
public void setCake(int c){
cake = c;
}
@Override
public void run() {
int m=2;//每次吃的数量
while (true){//死循环,一直吃
System.out.println();
if(cake<=0){
System.out.println(Thread.currentThread().getName()+"结束");
return;//没蛋糕,跳出循环
}
cake = cake -m;
System.out.println(Thread.currentThread().getName()+"吃了"+m+"份蛋糕");//Thread.currentThread()当前线程,然后再点name都行
System.out.println("还剩蛋糕"+cake+"份");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
结果:
最后
用Threa的子类实现多线程和使用Runnable接口实现多线程的区别 :
ps:最后一点已经说明了一切~~~~~