两个文件
第一个package shop.ljsp.learn.onebase.hunsafethreadprintln;public class MyThread extends Thread {
    private int i=5;    @Override
    public void run() {
        System.out.println("i="+(i--)+" threadName="+Thread.currentThread().getName());
    }
}第二个文件主文件package shop.ljsp.learn.onebase.hunsafethreadprintln;public class run {
    public static void main(String[] args) {
        MyThread run =new MyThread();
        Thread t1=new Thread(run);
        Thread t2=new Thread(run);
        Thread t3=new Thread(run);
        Thread t4=new Thread(run);
        Thread t5=new Thread(run);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}
运行第二个主文件后输出结果:
i=5 threadName=Thread-2
i=4 threadName=Thread-3
i=3 threadName=Thread-1
i=2 threadName=Thread-5
i=1 threadName=Thread-4
书里边显示的输出结果
i=5 threadName=Thread-1
i=2 threadName=Thread-5
i=3 threadName=Thread-4
i=4 threadName=Thread-3
i=4 threadName=Thread-2
请问这是什么原因造成的

解决方案 »

  1.   

    其实你再运行一次你的代码,结果可能又会不一样,这就是多线程,谁先执行由CPU决定
      

  2.   

    运行了很多次,前边的一直是递减,变的只是后面的
    i=5 threadName=Thread-1
    i=4 threadName=Thread-3
    i=3 threadName=Thread-4
    i=2 threadName=Thread-2
    i=1 threadName=Thread-5
    又来一次
    i=5 threadName=Thread-1
    i=3 threadName=Thread-2
    i=4 threadName=Thread-4
    i=2 threadName=Thread-5
    i=1 threadName=Thread-3
      

  3.   

    因为线程即使执行完System.out.println("i="+(i--)+" threadName="+Thread.currentThread().getName());  但是还没来得及打印,就被别的线程抢走了,等别的线程打印了,他可能抢到执行时间,才会打印,所以,这个前后都是会变化的,而且前面的数字不一定递减