• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread  RSS feed

 
kedar parundekar
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//Code->

class DemoThread extends Thread
{

Thread t1,t2;
DemoThread()
{
//t1=new Thread();
t1=new Thread(this); //<---------- why we reqd.this
t1.start();
}

public void run()
{
System.out.println("In run ()");
}
public static void main(String[] args)
{
DemoThread obj=new DemoThread();

}
}

Q ) If i run above program without passing "this" ref to const.of Thread
Then there is no output.
But if i run above program with passing "this" ref to const.of Thread
Then o/p is->In run ()

Why we required pass this ref to constructor of Thread class?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two ways to write code that can be run in a separate thread:

1. Subclass class Thread, put your own run() method in your subclass, and use your subclass to start a thread.

2. Make a class that implements Runnable, and create a new Thread object to which you pass an instance of your class, and start the thread.

You are mixing the two up.

You wrote a class that extends Thread (point 1 above), but then you use point 2 to start the thread. It works because class Thread implements Runnable, so your own subclass also implements Runnable.

Change your code to this (point 1):

or to this: (point 2):
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!