Nitesh
Nitesh

Reputation: 1

what do "this" means in multithreading in java?

t=new Thread(this,"clocky");
t.start();

This is the way of creating a new thread but I don't get why this is used.

Upvotes: 0

Views: 116

Answers (4)

Shafin Mahmud
Shafin Mahmud

Reputation: 4081

Lets start looking at java doc. You are actually calling this constructor

public Thread(Runnable target, String name)

java doc says

target - the object whose run method is invoked when this thread is started. If null, this thread's run method is invoked.

name - the name of the new thread

Here this refers the current object of the class where you are calling it, as it is in elsewhere in java. And I am sure your that class implements Runnable and overrides run() method. Thats how constructor parameter matches.

Upvotes: 4

vijayraj34
vijayraj34

Reputation: 2415

You must be implementing the Runnable interface in your current class and initializing the thread by passing the current runnable object using this keyword inside the constructor of your class.

It must be calling the run method while creating the instance of the runnable class like the below sample.

public class Nool implements Runnable {

    Thread t;

    public Nool() {
        t = new Thread(this, "Nool");
        t.start();
    }

    @Override
    public void run() {
        System.out.println("NOOL");
    }

}

I hope the explanation helps you.

Upvotes: 0

Abhishek
Abhishek

Reputation: 3398

Take a look

Multithread Basics

Simple Example

public class Test {

public static void main(String[] args) throws ParseException {


    Thread threadOne = new Thread(new Class_1(),"Class_1");
    Thread threadTwo = new Thread(new Class_2(), "Class_2");


    threadOne.run();  //This run calls run in Class_1
    threadTwo.run();  //This run calls run in Class_2


}

}

class Class_1 implements Runnable{
@Override
public void run() {
    System.out.println("Class_1 run method");
}
}

class Class_2 implements Runnable{
@Override
public void run() {
    System.out.println("Class_2 run method");
}
}

Output

Class_1 run method
Class_2 run method

Upvotes: 0

Paulo Mattos
Paulo Mattos

Reputation: 19339

Means that you are using the current object run() method, from the Runnable interface, as this thread main/starting method.

Upvotes: 1

Related Questions