线程休眠
采用Thread.sleep()
一个抢票的例子,三个线程同时访问一个静态资源,让票数递减,我们单独让一个线程休眠,比如500毫秒。
public class ThreadSleep {
//把票数设置为唯一
private static int stick=10;
public static void main(String[] args) {
//lambda表达式实现Runnable接口,并从写run()方法;
Runnable runnable=()->{
//如果当前线程是小明则线程睡眠5毫秒
try {
if(Thread.currentThread().getName().equals("小明")){
Thread.sleep(5);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
//让票数递减
while (true){
if(stick<=0){
break;
}
System.out.println(Thread.currentThread().getName