本帖最后由 杨兴庭 于 2013-7-25 23:00 编辑
为何出现死循环状况???求解
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;
}
}
}
}
|