简体   繁体   English

线程:不调用run方法

[英]Thread: Not calling run method

I am new in java. 我是java的新手。 Can someone help me why it is not calling Run method. 有人可以帮助我为什么不调用Run方法。 Thanks in advance. 提前致谢。

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");

}
}

You need to pass an instance of ThreadExample to the Thread constructor, to tell the new thread what to run: 您需要将ThreadExample的实例传递给Thread构造函数,以告诉新线程要运行的内容:

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

(It's unfortunate that the Thread class has been poorly designed in various ways. It would be more helpful if it didn't have a run() method itself, but did force you to pass a Runnable into the constructor. Then you'd have found the problem at compile-time.) (这是不幸的是, Thread类已经以各种方式被设计得不好。这将是更有帮助,如果没有一个run()方法本身,但没有强迫你一个通过Runnable到构造函数,然后你必须在编译时发现了这个问题。)

The run method is called by the JVM for you when a Thread is started. 在启动Thread时,JVM会为您调用run方法。 The default implementation simply does nothing. 默认实现什么都不做。 Your variable T is a normal Thread , without a Runnable 'target', so its run method is never called. 你的变量T是一个普通的Thread ,没有Runnable ',因此永远不会调用它的run方法。 You could either provide an instance of ThreadExample to the constructor of Thread or have ThreadExample extend Thread : 您可以向Thread的构造函数提供ThreadExample的实例,或者让ThreadExample 扩展 Thread

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

You can also do it this way.Do not implement Runnable in your main class, but create an inner class within your main class to do so: 你也可以做这种way.Do没有实现Runnable的主类,而是你中创建一个内部类main的类可以这样做:

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

Instantiate it from your Main class inside the main method: main方法中的Main类实例化它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM