implementing thread using runnable interface in java - java

Why we have to create an instance of a class and attach it to the newly created thread object even if both are in the same class?
import java.io.*;
class thread1 implements Runnable{
public void run(){
System.out.println("thread started");
}
public static void main(String args[]) throws Exception{
Thread t1=new Thread(new thread1());
t1.start();
}
}

You don't have to create a Runnable to perform custom code within a new Thread. It's also possible to create a subclass of thread directly.
public class WorkerThread extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
// DO SOMETHING
}
}
public class MainClass {
public static void main(String[] args){
new WorkerThread().start();
MainClass mc = new MainClass();
mc.startThread();
}
private void startThread(){
Thread t = new WorkerThread();
t.start();
}
}

I think you have two questions in one:
1.) How to work with a Thread in Java? The answer of Fizer Khan is an example of this.
2.) How do static methods work in java? If you have a static method you are, in a maner of speaking, on a "static layer". You have no "this" reference because there is not object on this layer. Only if you create an instance you can access instance fields and non static methods on this object.
If you add a second static method, you can do the same stuff as in your main method, because both are static. This is rudementary look at this question: https://stackoverflow.com/questions/18402564/how-do-static-methods-work
pulblic class Thread1 implements Runnable{ //name should be upper case
public void run(){
System.out.println("thread started");
}
public static void main(String args[]) throws Exception{ //static method
Thread t1=new Thread(new Thread1()); //t1 is a local reference to an object on the heap - no specil magic here
t1.start(); //call to an "instance" method, can only be performed on an object.
}

There are two ways to write threads.
public class ThreadX implements Runnable {
public void run() {
//Code
}
}
/* with a "new Thread(new ThreadX()).start()" call */
public class ThreadY extends Thread {
public ThreadY() {
super("ThreadY");
}
public void run() {
//Code
}
}
/* with a "new ThreadY().start()" call */
public class MainClass {
private Thread threadX = new Thread(new ThreadX());
private Thread threadY = new ThreadY();
public static void main(String[] args){
// Call threads
threadX.start();
threadY.start();
// some more threads
new Thread(new ThreadX()).start();
new ThreadY().start();
}
}
When you extends Threads, You usually extend a class to add or modify functionality. So, if you don't want to overwrite any Thread behavior, then use Runnable.

Related

Thread and super keyword

The following code will output Program A. Kindly explain it w.r.t super.run();.
class RunnableA implements Runnable{
public void run(){
System.out.println("Program A");
}
}
class MyThread extends Thread{
MyThread(Runnable r){
//set as a target
super(r);
}
public void run(){
//System.out.println("MyThread");
super.run();
}
}
class Demo{
public static void main(String args[]){
RunnableA a1=new RunnableA();
//a1.start(); //Illegal
new MyThread(a1).start();
}
}
super.run(); means that MyThread's run() method executes Thread's run() method (which calls the run() method of the Runnable instance that was passed to the constructor).
Therefore new MyThread(a1).start(); executes RunnableA's run() method and prints "Program A".
In this example MyThread is quite useless, as it doesn't add any functionality to Thread. You can replace your main method with :
public static void main(String args[])
{
RunnableA a1=new RunnableA();
new Thread(a1).start();
}
and get the same behavior.

Define method with object instantiation in java

I'm slowly transitioning from C++ to java and I do not understand the following piece of code:
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
System.out.println("out of run");
}
}
An object type "MyThreads" is being instantiated, but what does the function "void run" mean?
Why is it written using that syntax right after the object instantiation?
Is that function being overriden?
When is this kind of syntax (where I define a function with an object instantiation) necessary/required? and where is it preferred/useful?
It means that the class MyThreads either require you to first write a method with name run or the way you are doing provides the ability to change the existing run method behaviour where you are declaring.
It is like overriding if run method is already there or creating the method when you want to create object.
This provides the ability to create objects of MyThreads without having to change the original class or creating multiple classes.
public class TestThread
{
public static void main (String [] args)
{
Thread t = new MyThreads()
{
public void run()
{
System.out.println(" foo");
}
};
t.start();
Thread t1 = new MyThreads()
{
public void run()
{
System.out.println(" this time it is somethidn else");
}
};
t1.start();
System.out.println("out of run");
}
}
Little modification to your code shows the advantage of having this feature. If you observe run method of t1 is doing something different than what is in t. So it is now completely new thread.
This code is equivalent to
public class TestThread
{
static class MyThreadSubclass extends MyClass {
public void run() {
System.out.println("foo");
}
}
public static void main (String [] args)
{
Thread t = new MyThreadSubclass();
t.start();
System.out.println("out of run");
}
}
It's just a convenient way of defining a subclass inline, without having to give it a name; it's just syntactic sugar. It's creating an object of a subclass that overrides the method run() from MyThreads.

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

Callback from new thread to class from which thread was initiated

I have a class from which I am calling a new thread.
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
#Override
public void run() {
//Do Something
//After this I would like to notify my MainClass that some thing has been done and pass a value.
}
}
}
private void callbackFunc(int a){
// Do something based on value of a
}
}
I have a function in my MainClass. But how do i call this function from my new thread, so as to receive a callback.
Thanks.
You should just be able to call the method in MainClass by its name just as if you were calling from directly inside MainClass itself (as opposed to from the inner class).
If a method name you want to call happens to conflict with one that your inner class has inherited from Object then you can prefix the call with MainClass.this, e.g. MainClass.this.toString() calls toString on MainClass, whereas just toString() calls it on the inner class instance.
In such a case pass the instance of MainClass to the thread class ((during creation)) so that it can call method on it. Having inner class as suggested by others is also a good option.
Something similar-
class MainClass {
private void cleardata() {
new Thread(new MyThread(this)).start();
}
}
class MyThread implements Runnable {
private MainClass mc;
MyThread(MainClass mc) {
this.mc = mc;
}
public void run() {
// do something
// mc.someMethod();
}
}
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
#Override
public void run() {
callBackFunc(result);
}
}
}
private void callBackFunc(int a) {
}
}
Just do it:
public class MainClass{
private void cleardata() {
// do something on a separate thread
new Thread(new Runnable() {
#Override
public void run() {
//Do Something
notifyTheClass("a parameter");
}
}
private void notifyTheClass(String aParam) {
//..do something else
}
}
}
But it is not related to threads, this is about inner classes. If you want the main thread to wait until the new thread is finishes, use Futures for a result. Or use some other multithreading primitives.

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