public class Q1 implements Runnable
{
private int a;
public void run()
{
for(a=0;a<10;a++)
{
System.out.println(Thread.currentThread().getName()+":"+a);
try
{
Thread.sleep(100);
}catch(InterruptedException ex){throw new RuntimeException(ex);}
}
}
public static void main(String args[])
{
Q1 q=new Q1();
Thread t1=new Thread(q);
Thread t2=new Thread(q);
t1.start();
t2.start();
}
}
为什么输出两个0
{
private int a;
public void run()
{
for(a=0;a<10;a++)
{
System.out.println(Thread.currentThread().getName()+":"+a);
try
{
Thread.sleep(100);
}catch(InterruptedException ex){throw new RuntimeException(ex);}
}
}
public static void main(String args[])
{
Q1 q=new Q1();
Thread t1=new Thread(q);
Thread t2=new Thread(q);
t1.start();
t2.start();
}
}
为什么输出两个0
for(a=0;a <10;a++)
{
System.out.println(Thread.currentThread().getName()+":"+a);
try
{
Thread.sleep(100);
}catch(InterruptedException ex){throw new RuntimeException(ex);}
}
} 怎么会输出两个0?
Thread-0:0
Thread-1:0
Thread-0:1
Thread-1:2
Thread-0:3
Thread-1:4
Thread-0:5
Thread-1:6
Thread-0:7
Thread-1:8
Thread-0:9
这样才正常
Thread-0:0
Thread-1:0
Thread-1:1
Thread-0:1
Thread-1:3
Thread-0:3
Thread-1:4
Thread-0:4
Thread-0:5
Thread-1:5
Thread-1:6
Thread-0:6
Thread-0:8
Thread-1:8
Thread-0:10
//运行结果如下:
Thread-0:0
Thread-1:0
Thread-0:1
Thread-1:2
Thread-0:3
Thread-1:4 Thread-0:5
Thread-1:6
Thread-0:7
Thread-1:8
Thread-0:9
出现两个零是因为当时Thread-0:a为0后还没来的及变化值,Thread-1就开始执行了,所以此时Thread-1的a也为0。
Thread-0:0
Thread-0:1
Thread-1:2
Thread-0:3
Thread-1:4
Thread-0:5
Thread-1:6
Thread-1:7
Thread-0:8
Thread-0:9
楼主意思是为什么不是一个隔一个?线程分配的cpu时间片不是固定的~