sleep方法的签名:
public static void sleep (long millis)
sleep方法是Thread类的一个方法,作用是:在指定的毫秒内让正在执行的线程休眠(暂停执行)
参数为休眠的时间,单位是毫秒
package Threadproj;
class MyThread implements Runnable{
int i;
public void run() {
for(i = 1 ; i <= 10 ; i++) {
System.out.println(Thread.currentThread().getName()+"正在运行第"+i+"次");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class SleepDemo {
public static void main(String[] args)
{MyThread m = new MyThread();
Thread mt = new Thread(m);
mt.start();}
}
可以控制线程的刷新时间
线程的休眠时间也不仅仅和sleep有关的哦~
package Threadproj;
class MyThread implements Runnable{
public void run() {
for(int i = 1 ; i <= 10 ; i++) {
System.out.println(Thread.currentThread().getName()+"正在运行第"+i+"次");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class SleepDemo {
public static void main(String[] args) {
MyThread m = new MyThread();
Thread mt = new Thread(m);
mt.start();
Thread mt1 = new Thread(m);
mt1.start();
}
}
两个线程出现这样的结果是因为在休眠时另一个线程获得CPU的概率很大,所以出现了比较规律的交替执行的情况
!