创建了两个线程,一个不断进行复杂计算,另一个输出一些字符先start那个进行复杂计算的线程,可是发现似乎CPU就完全被这个线程占用了,而main线程就得不到执行了。于是thread2也得不到start和执行了。
但是书上是说CPU会分时间片让每个线程都得到执行的呀?
请高手指教public class TestInner { public static void main(String[] args) throws Exception {
TestThread1 thread1 = new TestThread1();
thread1.start();
TestThread2 thread2 = new TestThread2();
thread2.start();
}
}class TestThread1 extends Thread {
private volatile double d = 1;
public void run() {
while (true) {
d = d + (Math.PI + Math.E) / d;
System.out.println(d);
}
}
}
class TestThread2 extends Thread {
public void run() {
int i=9;
while (i--!=0) {
System.out.println("ff---------------------");
}
}
}

解决方案 »

  1.   

    要用sychronized让后用wait和notify去互相通知对方,在张孝祥的教程里有一个差不多的例子程序
      

  2.   

    while (true) {
    d = d + (Math.PI + Math.E) / d;
    System.out.println(d);
    }
    这个循环占了所有吧
      

  3.   

    我的问题是为什么CPU会被TestThread1完全占用。
    而不是怎么实现这个程序并行
      

  4.   

    to hwh_chizai(老子)
    你说的我想大家都看得出来吧 :)
      

  5.   

    线程2在 I= 0的时候退出了, 所以线程1占用了 100%的资源可以在线程1中加入适当的sleep来降低cpu消耗
      

  6.   

    楼上这位大哥,事实上i根本没机会到0!
    因为连TestThread2 thread2 = new TestThread2();
    这句都没机会执行请看清楚问题再回答,谢谢配合!