线程:不调用run方法

我是java的新手。 有人可以帮助我为什么不调用Run方法。 提前致谢。

package com.blt; public class ThreadExample implements Runnable { public static void main(String args[]) { System.out.println("A"); Thread T=new Thread(); System.out.println("B"); T.setName("Hello"); System.out.println("C"); T.start(); System.out.println("D"); } public void run() { System.out.println("Inside run"); } } 

您需要将ThreadExample的实例传递给Thread构造函数,以告诉新线程要运行的内容:

 Thread t = new Thread(new ThreadExample()); t.start(); 

(很不幸的是, Thread类的设计设计很糟糕。如果它本身没有 run()方法会更有帮助,但是它会强制你将Runnable传递给构造函数。然后你就会有在编译时发现了这个问题。)

Thread启动时,JVM会为您调用run方法。 默认实现什么都不做。 你的变量T是一个普通的Thread ,没有Runnable ‘,因此永远不会调用它的run方法。 您可以向Thread的构造函数提供ThreadExample的实例,或者让ThreadExample 扩展 Thread

 new ThreadExample().start(); // or new Thread(new ThreadExample()).start(); 

您也可以这样做。不要在主类中实现Runnable ,而是在主类中创建一个内部类来执行此操作:

 class TestRunnable implements Runnable{ public void run(){ System.out.println("Thread started"); } } 

main方法中的Main类实例化它:

 TestRunnable test = new TestRunnable(); Thread thread = new Thread(test); thread.start();