多線程
建立線程方式01
建立線程方式02
案例
package com.xiaoguoplus.demo;
/**
1. 案例題目描述:編寫龜兔賽跑多線程程式,設賽跑長度為100米
兔子每跑完10米休眠的時間10毫秒
3)提示:可以使用Thread.sleep(毫秒數)來模拟耗時
*
*/
public class Race implements Runnable{
//勝利者
private static String winner;
@Override
public void run() {
for(int i = 1;i <= 100; i ++){ //i 代表 米
//模拟兔子休息
if(Thread.currentThread().getName().equals("兔子")&&i%10==0){
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
//判讀比賽是否結束
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();
}
}
線程的四種狀态
同步
線程間通信
停止線程