线程在执行状态时,可以通过多种方式进行阻塞,每种阻塞的用法和用途都有差异,下面列举几个常用的阻塞方式。
sleep()
通过Thread类的sleep()方法,让线程暂停。通常使用该方法模拟网络延时。API中的描述:
通过一个龟兔赛跑的例子感受一下:
class Race implements Runnable {
public static volatile String winner = "";//冲线胜利者
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (Race.winner.equals("") || Race.winner == null) {
// 当未决出胜利者
if (Thread.currentThread().getName().equals("兔子") && i == 50) {
//兔子在第50步时睡觉了
try {
Thread.sleep(10);// 睡0.01秒,由于我电脑性能较好,100循环,基本只要sleep(),就跑不过了
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (i == 100) {
//100米,到终点了
Race.winner = Thread.currentThread().getName(); //胜利者
}
System.out.println(Thread.currentThread().getName() + "走了" + i + "米了");
}else{
// 已决出胜利者
System.out.println("获胜者是"+Race.winner); //由失败者线程,告诉我们谁赢了
break; //退出循环,不用跑了
}
}
}
}
public class Test {
public static void main(String[] args) throws InterruptedException {
new Thread(new Race(), "兔子").start();
new Thread(new Race(), "乌龟").start()