概述:
sleep(时间)指定当前线程阻塞的毫秒数
sleep存在异常InterruptedException;
sleep时间达到后线程进入就绪状态
sleep可以模拟网络延时,倒计时等
每一个对象都有一个锁,sleep不释放锁
//模拟网络延时:作用是放到问题的发生性
public class Main implements Runnable{
//票数
private int ticketNums=100;
public void run(){
while(true){
if (ticketNums>=0){
//模拟延时
try{
Thread.sleep(200);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第:"+ticketNums--+"票");//先拿到票再减减
}else{
break;
}
}
}
public static void main(String []args){
//创建线程实现类对象
Main t1=new Main();
//创建线程对象,并启三个线程把实现类对象添加到线程,然后为线程命名,注意多个线程操作一个对象是不安全的
Thread ead1=new Thread(t1,"线程1");
Thread ead2=new Thread(t1,"线程2");
Thread ead3=new Thread(t1,"线程3");
//启动线程
ead1.start();
ead2.start();
ead3.start();
}
}
//模拟倒计时
public class Main {
//倒计时方法
public static void tenDown() throws InterruptedException{
int num=10;
while(true){
//让线程这1秒钟跑一次,1000毫秒=1秒
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){//小于等于0,就结束
break;
}
}
}
public static void main (String[] args) {
//捕获一下,tenDown自己抛出的异常
try {
//调用倒计时方法
tenDown();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
//每秒打印系统当前时间
public class Main {
//倒计时方法
public static void tenDown() throws InterruptedException{
int num=10;
while(true){
//让线程这1秒钟跑一次,1000毫秒=1秒
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){//小于等于0,就结束
break;
}
}
}
public static void main (String[] args) {
//打印系统当前时间
Date seartTime=new Date(System.currentTimeMillis());//获取系统当前时间
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(seartTime));//"HH:mm:ss":设置获取系统时间的格式
seartTime=new Date(System.currentTimeMillis());//更新当前时间
} catch(Exception e) {
}
}
}
}