示例代码1:
public class mySleep {
public static void main(String[] args) {
MyThread t1 = new MyThread("tSleep123");
t1.start();
try {
Thread.sleep(100); //调用静态方法,可以无须创建对象实例
}
catch(InterruptedException e) {
return;
}
for(int i=0 ; i <3; i++) {
System.out.println(Math.random());
}
}
}
class MyThread extends Thread {
MyThread(String s) {
super(s);
}
public void run() {
for(int i = 1; i <= 3; i++) {
System.out.println("In "+getName());
try {
this.sleep(1000); //暂停,每一秒输出一次,通过this调用当前类成员,this可以省略
}catch (InterruptedException e) {
return;
}
}
}
}
示例代码1的运行结果
In tSleep123
0.33656215747187657
0.9286665377356843
0.31185034797492883
In tSleep123
In tSleep123
示例代码1用了thread继承演示sleep。
示例代码2:
public class MyRun implements Runnable {
public void run() {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
System.out.println("延时1秒钟");
try {
Thread.sleep(3000);
System.out.println("延时3秒钟");
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//构造方法:public Thread(Runnable target)
new Thread(new MyRun()).start();
}
}
示例代码2运行结果:
延时1秒钟
延时3秒钟
延时1秒钟
延时3秒钟
延时1秒钟
延时3秒钟
示例代码2用了实现Runnable接口演示sleep。