1、创建Wait类,让当前线程休眠
package com.ljb.app.thread;
/**
* 当前线程等待时间
* @author LJB
* @version 2015年3月9日
*/
public class Wait {
public static void bySec (long s) {
for (int i = 0 ; i < s ; i++) {
System.out.println(i + 1 + "秒");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
2、创建测试类
package com.ljb.app.thread;
/**
* 调用休眠方法,让主线程休眠5秒
* @author LJB
* @version 2015年3月9日
*/
public class TestSleep {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("wait");
Wait.bySec(5);
System.out.println("start");
}
}
运行结果:
wait
1秒
2秒
3秒
4秒
5秒
start
3、创建新线程NewThead
package com.ljb.app.thread;
/**
* 创建新线程,测试sleep运行后,该线程是否运行
* @author LJB
* @version 2015年3月9日
*/
public class NewThead extends Thread{
public void run () {
for (int i = 0 ; i < 5 ; i++) {
System.out.println(getName() + i);
}
}
}
4、测试类
package com.ljb.app.thread;
/**
* 调用休眠方法,让主线程休眠5秒
* @author LJB
* @version 2015年3月9日
*/
public class TestSleep {
/**
* @param args
*/
public static void main(String[] args) {
// 实例化
Thread newThread = new NewThead();
System.out.println("wait");
// 启动
newThread.start();
Wait.bySec(5);
System.out.println("start");
}
}
运行结果:
wait
1秒
Thread-00
Thread-01
Thread-02
Thread-03
Thread-04
2秒
3秒
4秒
5秒
start
描述:sleep只阻止当前线程,并释放系统资源,其余可运行线程运行