Thread: Not calling run method - java

I am new in java. Can someone help me why it is not calling 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");
}
}

You need to pass an instance of ThreadExample to the Thread constructor, to tell the new thread what to run:
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.)

The run method is called by the JVM for you when a Thread is started. The default implementation simply does nothing. Your variable T is a normal Thread, without a Runnable 'target', so its run method is never called. You could either provide an instance of ThreadExample to the constructor of Thread or have ThreadExample extend 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:
class TestRunnable implements Runnable{
public void run(){
System.out.println("Thread started");
}
}
Instantiate it from your Main class inside the main method:
TestRunnable test = new TestRunnable();
Thread thread = new Thread(test);
thread.start();

Related

How to understand this detailed multithreading and anonymous class related code?

public static void main(String[] args) {
new Thread(new Runnable() {
public void run() {
System.out.println("hello");
}
})
{
public void run() {
System.out.println("world");
}
}.start();
}
Simply I get "world" with this. Why it can be written in this manner? What is the first run() method for?
This (contrived) code passes an instance of an anonymous Runnable class to an instance of an anonymous Thread class that overrides its usual implementation of run().
It's becomes (a little) clearer if you refactor it:
// The runnable instance
Runnable runnable = new Runnable() {
public void run() {
System.out.println("hello");
}
};
// Anonymous Thread class with a custom run() method
new Thread(runnable) {
public void run() {
System.out.println("world");
}
}.start();
The Runnable passed to the Thread, which would be executed by the thread's start() method, is ignored because the Thread object is also an instance of an anonymous class with a custom implementation of its run() method, which is hard-coded to print "world".
This code creates an instance of an anonymous sub-class of Thread and then starts that thread.
That sub-class overrides Thread's run() method with a method that prints "world".
The first run() method is part of an anonymous implementation of the Runnable interface which is passed to the constructor of the Thread instance. That implementation is ignored, since your Thread implementation overrides run().
The Runnable instance passed to the thread constructor is only executed (when the thread starts) if the Thread's run() method is not overridden.
The Thread class defines run() in this way :
#Override
public void run() {
if (target != null) {
target.run();
}
}
It invokes the run() method of the Runnable instance (target field of Thread)if this field is not null.
So when you create an anonymous class of Thread that overrides this method in this way:
new Thread(...) {
#Override
public void run() {
System.out.println("world");
}
}
The Thread run() method of the anonymous instance doesn't rely any longer on the target field to run the Runnable instance.
It execute only this code :
System.out.println("world");
So the Runnable instance passed to the constructor of Thread is totally ignored by run():
new Runnable() {
public void run() {
System.out.println("hello");
}
}
You have overridden the run method which prints hello with the one which prints world. This happened because in your code you have extended the Thread class with an anonymous class which overrode the run method, therefore the Runnable parameter's run is never called. You can update the code to use super.run() to call the runnable method from the original class.
Here is your code with the changes:
new Thread(new Runnable() {
public void run() {
System.out.println("hello");
}
}) {
public void run() {
super.run();
System.out.println("world");
}
}.start();

Creating a thread is not working

I am trying to implement a thread into a project I am working on and I am not sure where i am going wrong.
package Project;
public class Launch{
public static void main(String[] args) {
Threads thread = new Threads();
thread.start();
}
}
class Threads implements Runnable{
static FruitSpawn spawn = new FruitSpawn();
public void run(){
spawn.spawnFruit();
}
}
The program is asking me to create a method called start() in Threads instead of stating the thread. Where am i going wrong in creating the thread? I am working in Java thanks.
Threads is just implementing Runnable not extending Thread so you can't call start() on it.
Do:
Thread t =new Thread(new Threads());
t.start();
You create a Thread, giving it your Runnable to run and then start it.
class Threads implements Runnable {
static FruitSpawn spawn = new FruitSpawn();
public void run() {
spawn.spawnFruit();
}
}
public void test() {
Threads spawner = new Threads();
Thread t = new Thread(spawner);
t.start();
}
you have to pass your Runnable to Thread class while initialization.
public class Launch{
public static void main(String[] args) {
Runnable runabl = new Threads();
Threads thread = new Threads(runabl);
thread.start();
}
}
class Threads implements Runnable{
static FruitSpawn spawn = new FruitSpawn();
public void run(){
spawn.spawnFruit();
}
}
Threads is implementing Runnable interface, and not extending Thread class. So, either you should
(a) Let Threads class implement Runnable and use
new Thread(new Threads()).start();
or
(b) Enhance Threads class to extend Thread class and not implement Runnable interface.
You can do some thing like:
Threads thread = new Threads(this);
thread.start();
thread.start() creates a new thread and have its own execution scenario. thread.start() calls the run method asyc.when come to running state.
Majorly speaking Thread Class has 4-flavour(other too but rarely used) of Constructor likewise,
1. Thread(),
2. Thread(String threadName),
3. Thread(Runnable target),
4. Thread(Runnable target, String threadName).
Now you have Threads class which implements Runnable Interface.
So Object of Threads class called Runnable type Object.
Now you have to pass that Threads class Object into 3rd flavor of Thread Class constructor.
so do following changes in your code and enjoy !!
public class Launch{
public static void main(String[] args) {
Threads runnableObject= new Threads();
Thread t = new Thread(runnableObject); // among of above listed 3rd flavor of Thread class constructor.
t.start(); // start thread which will call run() of Threads Class.
}
}

getName() from class Thread

Why do I have access to the getName() method? My class doesn't extends the class Thread just implements the interface Runnable.
public class MyThread implements Runnable {
public void run() {
System.out.println("MyThread is running");
}
public static void main(String[] args){
MyThread thread1 = new MyThread();
Thread thr = new Thread(thread1, "thread");
thr.start();
System.out.println(thr.currentThread().getName());
System.out.println(thr.getName());//Why do I have access to this method?
}
}
You're not calling getName() on an instance of the MyThread class, you're calling it on an instance of the Thread class. You should consider renaming your class to MyRunnable because MyThread would seem like your class is some sort of Thread class, while it isn't.
Every action you perform is in a thread. In case you are doing some action, in the main method while starting the program, it happens in the main thread.
The method currentThread is static, and it provides the thread that is currently executing that line and when you perform, getName() it is on that Thread object.

Java Thread Creation

I am trying to create a thread using runnable method .The code is below
public class NewClass implements Runnable{
public static void main(String[] agrg){
NewClass n =new NewClass();
n.start();
}
void start(){
Thread th=new Thread();
th.start();
}
#Override
public void run() {
System.out.println("Thread");
}
}
In this override method run should me call ,but it is not happening
Your run() method is belong to NewClass which is not a Thread, it's a worker.
So, no body going to call run() method of NewClass
In java, when you are creating a worker by implementing Runnable, you should override the run() method only. And pass an instance of this worker to a Thread, like
new Thread(new NewClass()).start();
So you can do the following
public class NewClass implements Runnable{
public static void main(String[] agrg){
NewClass n =new NewClass();
n.start();
}
void start(){
Thread th=new Thread(this);
th.start();
}
#Override
public void run() {
System.out.println("Thread");
}
}
You need to pass the Runnable instance to the Thread class constructor.
In your case, replace Thread th=new Thread(); with Thread th=new Thread(new NewClass()).
When you create a Thread class instance using Thread th=new Thread(); the default implementation of the Thread.run() method is invoked (which does nothing).
Thus, you need override the run() method in your implementing class (NewClass in your case) which you have done correctly. But you also need to specify the implementing class instance to the Thread class constructor using Thread th=new Thread(new NewClass())
You are starting a new Thread, but that thread isn't actually doing anything. The new thread has no connection whatsoever to the class it is started from or the code that class contains.
When you implement a Runnable, you usually perform it by creating a thread with that runnable as an argument.
Runnable myRunnable = new NewClass();
Thread myThread = new Thread( myRunnable );`
myThread.start(); // will execute myRunnable.run() in background
or by using an Executor.
Executor myExecutor = new SheduledThreadPoolExecutor(NUM_OF_PARALLEL_THREADS);
Runnable myRunnable = new NewClass();
myExecutor.execute(myRunnable); // will execute myRunnable.run() in background as soon as one of the parralel threads is available
Your Thread class is a separate class from your main class.
public class ThreadClass implements Runnable {
#Override
public void run() {
System.out.println("Thread");
}
}
public class MainClass {
public static void main(String[] agrg) {
ThreadClass t = new ThreadClass();
Thread th = new Thread(t);
th.start();
}
}
As mentioned earlier, no one is there to run your "run" method. You can extend Thread and can ask the run method to do the work just by starting the Thread
public class NewClass extends Thread{
public static void main(String[] agrg){
NewClass n =new NewClass();
n.start();
}
#Override
public void run() {
System.out.println("Thread");
}
}

How to invoke two run methods in one java file

below is the code where i need to invoke 2 run methods for 2 different threads any way this can be done. please help on this.
public class QuestionList extends ListActivity implements Runnable {
//This below thread will call the run method
Thread thread = new Thread(QuestionList.this);
thread.start();
//can i have one more thread which call run1() method any idea
}
public void run() {
}
You cannot have two run() methods of course, and I suggest not using the same for both Threads (with a of if() statement to determine which behaviour to apply).
Instead you should create two distinct classes (why not inner classes) to implement these distinct behaviours. Something like:
public class QuestionList extends ListActivity {
class BehaviourA implements Runnable {
public void run() {
}
}
class BehaviourB implements Runnable {
public void run() {
}
}
private void somewhereElseInTheCode() {
BehaviourA anInstanceOfBehaviourA = new BehaviourA();
Thread threadA = new Thread(anInstanceOfBehaviourA);
threadA.start();
BehaviourB anInstanceOfBehaviourB = new BehaviourB();
Thread threadB = new Thread(anInstanceOfBehaviourB);
threadB.start();
}
}
The good thing with inner classes is that they can access to the members of QuestionList, and this seems to be what you are willing to do.
public class QuestionList extends ListActivity {
//This below thread will call the run method
Thread1 thread1 = new Thread(this);
thread1.start();
Thread2 thread2 = new Thread(this);
thread2.start();
}
class Thread1 implements Runnable
{
public void run() {
}
}
class Thread2 implements Runnable
{
public void run() {
}
}

Categories