public static void main(String[] args) { final Thread t1 = new Thread() {
public void run() {
while (true) {
System.out.println("AAAAAAA");
}
};
}; Thread t2 = new Thread() {
public void run() {
while (true) {
// t1.stop();
// t1.suspend();
                                              Thread.sleep(2000);
try {
t1.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
}; t1.start();
t2.start();
}如上代码~ 我想用t2来控制t1的输出~ 使得t1每隔2秒睡眠1秒 ~可以t1还是那样地快速不断输出
难道进入了死循环的线程不能休眠? 如果我把sleep换成suspend或者stop却能执行~
求教高手~ 怎样解决~~急

解决方案 »

  1.   

    基础很重要,lz线程的基础还没有搞清楚,sleep方法是Thread类的静态方法,只对当前进程起作用
      

  2.   

    final Object o = new Object();

            final Thread t1 = new Thread() {
                public void run() {
                    while (true) {
                     synchronized (o) {
                        System.out.println("AAAAAAA");
                        try {
                        o.notify();
                         o.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
                     }
                    }
                };
            };        Thread t2 = new Thread() {
    public void run() {
                    while (true) {
                     synchronized (o) {
                        try {
                        o.notify();
                            sleep(1000);
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                     }
                    }
                };
            };        t1.start();
            t2.start();