各位大神好,求支援
我在做线程的时候遇到了个问题
循环退不出来
public class ThreadTest4
{
public static void main(String[] args)
{
// 使用同一个Runnable对象创建两个线程
Runnable r = new Runnable1();

Thread t1 = new Thread(r);
Thread t2 = new Thread(r);

t1.start();
t2.start();
}
}class Runnable1 implements Runnable
{
int i;

@Override
public void run()
{
while(true)
{
// 此情况能够正常退出
i++;
System.out.println("Runnable1: " + i);

try
{
Thread.sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e)
{
e.printStackTrace();
} if(i == 5)
{
break;
}

}
}
}
还有个不能够正常退出。
public class ThreadTest4
{
public static void main(String[] args)
{
// 使用同一个Runnable对象创建两个线程
Runnable r = new Runnable1();

Thread t1 = new Thread(r);
Thread t2 = new Thread(r);

t1.start();
t2.start();
}
}class Runnable1 implements Runnable
{
int i;

@Override
public void run()
{
while(true)
{
try
{
Thread.sleep((long)(Math.random() * 1000));
}
catch (InterruptedException e)
{
e.printStackTrace();
}// 此情况不能够退出
i++;
System.out.println("Runnable1: " + i); if(i == 5)
{
break;
}

}
}
}
javathread线程,

解决方案 »

  1.   

    可能是因为 Thread.sleep((long)(Math.random() * 1000));
      

  2.   

    就和判断i 的值的时机有关:
    1     能够正常退出时,是两个线程都能检测到i==5,代码是先进行递增,后休眠,再判断。假设某个时刻i=4,某个线程运行i++时,i=5. 这个线程休眠,另一个线程此时肯定也在休眠中,这时不管哪个线程休眠结束,i都是5,线程结束。
    2     对于先休眠,后递增,再判断的情况,假设某个时刻i=4, 当一个线程休眠结束,执行i++,i=5,此线程结束了。而另一个线程休眠结束后,执行i++,i=6,就不会结束了。
    3     楼主可以把
    System.out.println("Runnable1: " + i);
    换成:
    System.out.println(Thread.currentThread().getName() +" "+ i);
    会看得清楚点。
      

  3.   

    if(i == 5)
    改成
    if(i >= 5)
      

  4.   

    就是线程没有用synchronize来控制资源,你这种情况有可能i会跳过5的,所以一直在运行这,跳不出来。