sleep

来源:互联网 发布:seo和sem的区别与联系 编辑:程序博客网 时间:2024/05/22 06:48

线程休眠使用sleep(long millis)

注意:sleep()是静态方法(数据在内存中只有一份,能够被一个类的所有实例对象所共享),只能控制当前正在运行的线程,而不能控制其他线程休眠。当休眠结束之后,线程就会返回到就绪状态,而不是立即开始运行。

package study;
public class Example08 {
public static void main(String[] args)  throws Exception{
new Thread(new SleepThread()).start();
for(int i=0;i<10;i++){
if(i==5){
Thread.sleep(2000);
}
System.out.println("主线程正在输出:"+i);
Thread.sleep(500);
}
}
}
class SleepThread implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<10;i++){
if(i==3){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
System.out.println("线程一正在输出:"+i);
try{
Thread.sleep(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}

结果:


原创粉丝点击