• Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread Query  RSS feed

 
abin joy
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code
----------------------

public class ThreadinArg extends Thread {

public static void main(String[] args) {
//Thread t=new Thread(new ThreadinArg());
ThreadinArg t=new ThreadinArg();
t.start();
}
public void run(){
for (int i = 0; i < 3; i++) {
System.out.println("hi");
}
}

---------------------------
code

what is the advantage in directly instantiating the thread and calling start rather passing the Thread Constuctor?
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use the code button and indentation; your code is difficult to read.

Will that actually compile without the // comment? Thread doesn't have a constructor which takes Object or Thread as a parameter.

Doesn't sound like a beginner's question. Moving.
 
Steve Luke
Bartender
Posts: 4181
22
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread does not have a Thread(Thread toRun) constructor, but it does have a Thread(Runnable toRun) constructor, and a Thread implements Runnable.

what is the advantage in directly instantiating the thread and calling start rather passing the Thread Constuctor?


The benefit here would go to instantiating the thread and calling start. Passing an instance of the Thread to a constructor for a new Thread simply adds a second thread instance to the mix. You get all the overhead of the Thread object twice, but only use one of them.

The usual choice is between sub-classing Thread and directly starting it, or passing in a Runnable implementation. The difference here is mostly design. When you subclass a Thread you are suggesting that you are adding/changing the functionality of Thread. When you pass a Runnable, you are saying you have a task that should run in a normal Thread. Most often you aren't changing how the Thread behaves, so you shouldn't subclass it. Most often you are just providing a unit of work which should be done in its own thread, which is what a Runnable is, so you should implement a Runnable.

To fix the code you provided in post 1, you would change it to:
 
Campbell Ritchie
Sheriff
Posts: 53779
128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steve Luke:
Thread implements Runnable.


I had forgotten that. Thank you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!