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

解决方案 »

  1.   

    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();
    }
    }
      

  2.   

    为什么单线程就不能用Thread.sleep() ?
      

  3.   

    好像不行啊,会报java.lang.IllegalMonitorStateException的错,我的程序是这样测试的。Thread t = new Thread(){
    TestObj t1 = new TestObj();
    TestObj t2 = new TestObj();

    public void run() {

    while(true) {
    try {
    Thread.sleep(1000);
    t1.print("1");
    t2.wait(2000);
    t2.print("2");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    };
    t.start();
      

  4.   

    单线程sleep其它的对象就不工作了
      

  5.   

    是没有加synchronized报的错,但还是不行,t2对象等待后还是会整个线程还是会等待,我想实现的是t1不断打印,t2迟5秒后再打印,也就是说t1一定打印得比t2多,但现在不是这效果。
      

  6.   

    没有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);
     
    }
    }
    }
    }