java笔记--线程休眠sleep()的运用
线程休眠sleep()方法的运用
在多线程编程中,有时需要让某个线程优先执行。除了可以设置这个线程的优先级为最高外,
更加理想的方法是休眠其他线程,若有线程中断了正在休眠的线程,则抛出InterruptedException.
--如果朋友您想转载本文章请注明转载地址"http://www.cnblogs.com/XHJT/p/3894793.html "谢谢--
sleep()方法是Thread类的一个静态方法,主要实现有:
sleep(long millis) : 让线程休眠指定的毫秒数
sleep(long millis,int nanos) : 让线程休眠指定的毫秒数加纳秒数
代码实例:
package com.xhj.thread;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 用龟兔赛跑来描述sleep()的作用
*
* @author XIEHEJUN
*
*/
public class SleepThread implements Runnable {
/**
* 执行兔子赛跑线程
*/
@Override
public void run() {
for (int i = 1; i < 11; i++) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
// 格式化当前日期
SimpleDateFormat sdf = new SimpleDateFormat("k:m:s");
String result = sdf.format(new Date());
System.out.println("系统时间:" + result + "\t兔子跑了" + i * 10 + "米");
if (i == 9) {
System.out.println("没见到乌龟的身影,兔子偷笑的找个地方睡觉去了……");
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
}
if (i == 10) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("兔子到达终点");
}
}
}
/**
* 执行乌龟赛跑线程
*
* @return
*/
public Thread turtle() {
class Turtle implements Runnable {
@Override
public void run() {
for (int i = 1; i < 21; i++) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
// 格式化当前日期
SimpleDateFormat sdf = new SimpleDateFormat("k:m:s");
String result = sdf.format(new Date());
System.out.println("系统时间:" + result + "\t乌龟跑了" + i * 5+ "米");
if (i == 20) {
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("乌龟到达终点");
}
}
}
}
Thread thread = new Thread(new Turtle());
return thread;
}
public static void main(String[] args) {
SleepThread sleep = new SleepThread();
Thread rabthread = new Thread(sleep);
Thread turThread = new Thread(sleep.turtle());
System.out.println("比赛开始:");
rabthread.start();
turThread.start();
}
}