package hqb;public class C125 { /**
 * @param args
 */
int x=0;
public class Runner implements Runnable{
public void run(){
int current=0;
for(int i=0;i<4;i++){
current=x;
System.out.print(current+" ");
x=current+2;
}
}
}
public static void main(String[] args) {
// TODO 自动生成方法存根
new C125().go(); }
public void go(){
Runnable r1=new Runner();
new Thread(r1).start();
new Thread(r1).start();
}}
我测试了一下得到很多结果:
0 2 4 4 6 8 10 6
0 2 4 6 8 10 12 14
0 0 2 4 6 8 10 12
0 0 2 2 4 4 6 6
0 2 4 0 6 2 4 6
0 0 2 4 6 2 4 6

就后面两种不理解,不知道为什么又倒回去了,望高人指点!

解决方案 »

  1.   

    System.out.print(Thread.currentThread().getName()+"  "+current+"");
    打印的时候这样输出试试
      

  2.   

    回复1楼:
    我试了一下:Thread-0,0  Thread-1,0  Thread-0,2  Thread-0,4  Thread-0,6  Thread-1,2  Thread-1,4  Thread-1,6
              Thread-0,0  Thread-0,2  Thread-0,4  Thread-0,6  Thread-1,8  Thread-1,10  Thread-1,12  Thread-1,14  
    针对这两个结果,第一个是两个线程操作各自的全局变量x,所以最大为6;而对第二个结果,两个线程都是操作同一个x,所以最后结果为14;
    ···
    我知道对线程的操作是没有保障的,但是不知道为什么会出现以上的结果?
      

  3.   

    可以理解的,线程调度由cpu进行,而在程序没有做限制的时候,在任何程序的位置都可能被抢走cpu时间片0 2 4 0 6 2 4 6 
        int x=0;
        public class Runner implements Runnable{
            public void run(){
                int current=0;
                for(int i=0;i<4;i++){
                    current=x;           《-- 线程1在这里被线程2抢占cpu,此时线程1的current=0,然后线程2继续运行,打印出 0 2 4,然后又转回线程1,打印出0
                    System.out.print(current+" "); 《--执行完这一句后,线程1又被抢走cpu资源,此时current=0;而x=6;线程2继续打印6,然后又转回线程1执行,将x赋值为2
                    x=current+2;
                }
            }
        }
      

  4.   

    原因上面其实已经都说了
    主要x是类变量,而current是线程内变量
    类变量对于线程Runner类来说是全局的而且线程的执行是未知的,线程调度不同,产生的结果也不同
      

  5.   

    我想是不是能这样理解,线程随时都有抢占cpu资源的可能,即使是在一个完整的for循环里面!
      

  6.   

    线程占有的cpu的时间片是不好把握的,线程之间都在抢占有限的CPU资源,一个线程的时间片到了,它就得让出时间片给别的线程。