Subject: Do not run the method

I am new to java. Can someone help me why it is not calling the Run method. 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"); } } 
+3
source share
3 answers

You need to pass the ThreadExample instance to the Thread constructor to tell the new thread to start:

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

(Unfortunately, the Thread class was poorly designed in various ways. It would be more useful if it did not have a run() method, but made you pass Runnable to the constructor, then you would find the problem at compile time.)

+4
source

The run method is called by the JVM for you when Thread starts. The default implementation just does nothing. Your T variable is a normal Thread , without a Runnable 'target', so its run method is never called. You can either provide an instance of ThreadExample the Thread constructor, or ThreadExample extend Thread :

 new ThreadExample().start(); // or new Thread(new ThreadExample()).start(); 
+2
source

You can also do it this way. Do not implement Runnable in your main class, but create an inner class in your main class to do this:

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

Create it from the main class inside the main method:

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

Source: https://habr.com/ru/post/1013226/


All Articles