2013-01-04 166 views
1

新的多线程和我遇到了一些问题和困惑。 :)多线程控制台输出不同

public class NewThread implements Runnable { 

    Thread t; 

    NewThread() { 
     t = new Thread(this, "Demo Thread"); 
     System.out.println("Child Thread " + t); 
     t.start(); 
    } 

    @Override 
    public void run() { 

     try { 
      for (int i = 5; i > 0; i--) { 
       System.out.println("Child Thread: " + i); 
       Thread.sleep(500); 
      } 
     } catch (InterruptedException e) { 
      System.out.println("Child Interrupted."); 
     } 

     System.out.println("Exiting Child Thread."); 
    } 

} 

class ThreadDemo { 

    public static void main(String[] args) { 

     NewThread t = new NewThread(); 

     try { 
      for (int i = 5; i > 0; i--) { 
       System.out.println("Main Thread: " + i); 
       Thread.sleep(1000); 
      } 
     } catch (InterruptedException e) { 
      // TODO: handle exception 
      System.out.println("Main Thread Interrupted."); 
     } 

     System.out.println("Main Thread Exiting."); 
    } 

} 

的例外输出

enter image description here

我的输出

enter image description here

为什么我的控制台输出与预期输出有什么不同?谢谢。

+0

你确定你有'NewThread t = new NewThread();'main? –

+0

是的,看起来像。 – AppSensei

+0

src对我来说很不错。我能够执行你的源代码并获得正确的输出。你确定这里发布的src和你正在测试的一样吗? – Jayamohan

回答

0

NewThread类中的变量t不是NewThread类型,所以它永远不会执行子线程循环。你永远不会在NewThread对象上调用start(),所以它看起来没有任何执行输出。

System对象是静态的,并且由在此VM上执行的所有线程共享。

+1

在_NewThread_类的构造函数中调用start()方法。你检查过了吗? – Jayamohan

+0

你可以把它写成代码吗? – AppSensei

+0

在实际执行代码之后,我将不得不重新执行此操作,我将得到“预期的输出” –

-3
class ThreadDemo { 

public static void main(String[] args) { 

    NewThread t = new NewThread(); 

    try { 
     for (int i = 5; i > 0; i--) { 
      System.out.println("Main Thread: " + i); 
      Thread.sleep(1000); 
      t.run(); //// forgot here 
     } 
    } catch (InterruptedException e) { 
     // TODO: handle exception 
     System.out.println("Main Thread Interrupted."); 
    } 

    System.out.println("Main Thread Exiting."); 
} 

}

附加t.run();

+1

线程的要点如果我从main()函数调用''t.run()'' ''方法手动? – 2013-01-04 02:01:32

+0

@ user1947279您的't.run()'调用不仅会在主线程上运行,而且还会在for循环的每次迭代中运行 – Ryan

0

我会认为问题在于你的NewThread类的构造函数没有被调用。关于你的构造

NewThread() { 
     <STUFF> 
    } 

怪异的一部分是doen't有一个访问修饰符,即它缺少public关键字。这使得构造函数包是私有的。如果您ThreadDemo类是在不同的包,将无法看到构造函数,构造函数将随后不会当你调用

NewThread t = new NewThread(); 

因此,我认为你应该只添加public执行关键字给你的构造函数,一切都很好。或者将NewThreadThreadDemo类放在同一个包中。

+0

@Appsherif您可以检查这是否正确,如果接受答案? – MarcFasel

0

该代码,你发布是好的!我有你的预期输出!

我怀疑你是从其他代码开始的,你用你的main中的其他变量“t”覆盖变量“t”。也许你宣布你的代码的一部分是静态的。