public class Main extends Thread{
    private int i ;
    public void run(){
        for ( ; i < 100 ; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
        }
    }
    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 100 ; i++) {
            System.out.println(Thread.currentThread().getName() + " " + i);
            if (i == 20){
                new Main().start();
                new Main().start();
            }
        }
    }
}
为什么在Main线程执行完之后才执行Thread-0线程?在Thread-0之后才执行Thread-1线程?不是应该在i = 20时就执行吗?
用的idea编辑运行,jdk1.8

解决方案 »

  1.   

     把for循环中的判断条件100改成1000试试,或者把线程堵塞500毫秒运行一次,我这边试了试都是并发运行的。
      

  2.   

    很奇怪我用idea1.8的jdk就都是同步的效果,而用myeclipse1.6的jdk就是并行
      

  3.   

    即使Thread.sleep(1000) idea也是同步执行进程
      

  4.   

    for (int i = 0; i < 100 ; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
                try{
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (i == 20){
                    new test().start();
                    new test().start();
                }
            }
      

  5.   

    调用Thread.start();时Thread0只是有了执行权并不是立即执行(取决于CPU的选择),所以当Thread0执行时main线程可能已经执行完了。当我们用Thread.sleep(10).主线程会停掉,这时候会调用Thread0。
      

  6.   

    只能说明你的电脑太差了,可以扔了。windows是时间片抢占机制的,一个那么小的东西运行起来,别的线程都没资源了,你是神马配置啊。越高档的电脑,额外线程启动应该越快,越接近20就启动(如楼主代码一样没有任何Sleep让时间片)。楼主敢不敢贴出来,你电脑有多烂
      

  7.   

    public class Main extends Thread{
        private int i ;
        public void run(){
            for ( ; i < 100 ; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
            }
        }
        public static void main(String[] args) throws InterruptedException {
            for (int i = 0; i < 100 ; i++) {
                System.out.println(Thread.currentThread().getName() + " " + i);
                if (i == 20){
                    Thread.sleep(500);
                    new Main().start();
                    new Main().start();
                }
            }
        }
    }
    欢迎光临我的博客
    http://happyshome.cn