process:进程 thread:线程 jdk中Thread extends Object implement Runnable 所以在extends thrread、implement runnable是一样的道理
创建线程过程: 1.extends thread->重写run()方法->在main()方法中创建线程对象,调用start()。 2.implements Runnable->重写run()方法->创建runnable()接口的实现类对象,创建Thread()对象,来开启线程:::用thread()来代理
总结:thread也是继承了runnable()接口,启动时都要创建有关thread()的对象来启动。
龟兔赛跑
public class race implements Runnable{ private static String winner; @Override public void run() {
for(int i=0;i<=100;i++){
boolean flag=gameover(i);
if(flag) break;
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
private boolean gameover(int steps){
if(winner!=null) return true;
if(steps>=100){
winner=Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
return false;
}
public static void main(String[] args) {
race race = new race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
|