日期:2014-05-20  浏览次数:20713 次

单线程睡眠问题
我现在遇到个问题,就是我的框架是单线程的,所以不能用Threed.sleep()这种方式,但我的程序又不方便用JAVA的定时器。原因我需要在同一方法中System.out.println()后延迟1分钟再打印另一个System.out.println(),我现在的做法是用while循环对比时间,但如果同时有一百个对象这样做的话会对CUP损耗较大,大家有没有更好的方法呢。

------解决方案--------------------
object.wait(时间);
------解决方案--------------------
public class Mytest {
public void print() {
System.out.println("123");
}

public void print2() {
System.out.println("1234");
}

public static void main(String[] arg) throws InterruptedException {
Mytest test = new Mytest();
test.print();
synchronized(test){
test.wait(2000);
}
test.print2();
}
}

------解决方案--------------------
引用:
你这是要在单线程下创造多线程,要自己构造程序的执行过程,你这是既当爹又当妈

------解决方案--------------------
没有timer就自己实现一个timer呗
timer的本质还不就是循环计时。



//实现自己的timer
class MyTimer 
{
//用于累加周期,我就不考虑数据溢出啥的了,估计也溢出不了
long start = 0L;
long end = 0L;
//控制时钟周期
final long invet = 2000L;
//这个运算可能要消耗1ms 忽略不计
boolean action()
{

start = System.currentTimeMillis();

if (start > end)
{
end = start + invet;
return true;
}
else
{
return false;
}
}
}

public class TimerTest
{
public static void main(String[] args) throws Exception
{
MyTimer timer = new MyTimer();
while (true)
{
System.out.println("t1");

if (timer.action())
{
System.out.println("t2-------------------我来了");
//为了方便看效果,停一下
Thread.sleep(100);
 
}
}
}
}