开发者

How can it possible that after implementing Runnable interface in java Thread methods are call?

How can it possible that after implementing Runnable interface in开发者_开发问答 java Thread methods are call?


I think you need to read up on basic threads. Check out this page, specifically look at the example under the heading "Creating and starting threads"


Are you passing your Runnable implementation to the Thread constructor?

This is the recommended way to create and start a thread:

class MyRunnable implements Runnable {
    public void run() {
        System.out.println("Hello, World!");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

Is this similar to how you are attempting it?

Some common gotchas with Java threads:

  • Calling thread.run() instead of thread.start()
  • Calling a static method through an instance, e.g. thread.sleep(1000) makes the current thread sleep, not the target thread.


I'm presuming that you are having this question because when Runnable interface is implemented what is provided is implementation for method run(). And we don't make any explicit invocation of run method to start the Thread.

In the below exmaple (from Java tutorial) the Thread is started by invoking the start() method:

public class HelloRunnable implements Runnable {

    public void run() {
        System.out.println("Hello from a thread!");
    }

    public static void main(String args[]) {
        (new Thread(new HelloRunnable())).start();
    }

}

And if you look at javadoc for the method 'start()` of Thread class in the JAVA API, this is what it says:

start public void start()

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).


At any time, from anywhere, you can call Thread.currentThread() to get a reference to the currently-running thread, if that helps. If you need to override methods from the Thread class, you'll need to inherit from it rather than implementing Runnable, but there's not usually a good reason to do that.


It is made possible by using Thread class constructor .otherwise it is not possible at all.

class ImplementsRunnable implements Runnable {
public void run() {
 System.out.println("ImplementsRunnable");
 }
 } 
public class DemoRunnable {
  public static void main(String args[]) throws Exception {
             ImplementsRunnable rc = new ImplementsRunnable();
             Thread t1 = new Thread(rc); 
             t1.start();
  /*here with the help of Constructor of Thread Class we call start method which is not in ImplementsRunnable*/
}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜