
可以使用sleep()方法。
sleep()方法拥有一个参数,它控制睡眠的长短,以毫秒计算。sleep()方法会抛出InterruptedException,所以一定在try-catch块里面使用它。
示例代码如下:
public class A implements Runnable{int i = 0
public static void main(String[] args){
A a1 = new A()
A a2 = new A()
a1.run()
a2.run()
}
public void run(){
while(++i <= 100){
System.out.println(i)
try{
Thread.sleep(50)
}catch(Exception e){
e.printStackTrace()
}
}
}
}
注意,sleep()方法并不保证线程醒来后进入运行,只能保证它进入就绪状态。
前段时间从windows移植了一个程序到linux上,不知为何性能奇差。查了下原因,发现是由于一个函数ZeroSleep特别耗时,这个函数的代码很简单,如下:void ZeroSleep()
{
Sleep(0)
}
Sleep(0)作用是用来释放cpu的时间片,避免忙等待。于是想当然的在linux上实现为:
void ZeroSleep()
{
msleep(0)
}
但其实msleep API的源代码如下:
void msleep(unsigned int msecs)
{
unsigned long timeout = msecs_to_jiffies(msecs) + 1
while (timeout)
timeout = schedule_timeout_uninterruptible(timeout)
}
如此一来,即使参数为0,也至少要睡眠一个jiffies单位的时间,因此导致严重的性能问题。
该问题的解决方法是:
既然ZeroSleep的目的是释放cpu资源,那么就可以通过调用schedule()函数替换msleep 。而且实际上msleep本身也是通过调用schedule_timeout_uninterruptible实现的,所以这个做法也是合理的。
http://tassardge.blog.163.com/blog/static/17230170820100275580656/
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)