0

When writing a Thread in Java (for example for handling different clients in Java):

1) What should be the reasons for doing it by extending Thread class, or by implementing Runnable interface?

2) How is it possible to give the newly created thread a name for accessing it in the program?

3) How to avoid situation that some threads have the same name?

Day_Dreamer
  • 3,311
  • 7
  • 34
  • 61
  • 1
    Please ask one question per question. – Pshemo Mar 06 '15 at 14:53
  • 1
    [SO explaining extends Threads vs implements Runnable](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread) – gtgaxiola Mar 06 '15 at 14:53
  • The Rubnable interface is preferred. – CaffeineToCode Mar 06 '15 at 14:56
  • 1
    "What should be the reasons for doing it by extending Thread class" I actually didn't see any pros of extending Thread, only cons. Thread is class responsible for executing task, not for being the task. Always prefer implementing Runnable over extending Thread to avoid problems like invoking `notifyAll` when Thread task will be finished (which doesn't happen when you pass `Runnable`). – Pshemo Mar 06 '15 at 15:02
  • How does it avoids them? – Day_Dreamer Mar 06 '15 at 15:03

3 Answers3

2

Some words about 1):

Implementing Runnable makes your class more flexible.

A class that implements Runnable is not a thread and just a class. For a Runnable to become a Thread, You need to create an instance of Thread and passing itself in as the target.

By extending Thread, each of your threads has a unique object associated with it, whereas implementing Runnable, many threads can share the same runnable instance.

In most cases, the Runnable interface should be used if you are only planning to override the run() method and no other Thread methods. This is important because classes should not be subclassed unless the programmer intends on modifying or enhancing the fundamental behavior of the class.

About 2)

The name of the Thread below is [myThread]

Thread myThread =new  Thread(new Runnable(){
  public void run(){

  //code

  }});

myThread.start(); //start it

About 3)

About names... If you dont care to access the Thread by name like the example above you can just a Thread and into it add code that has a behavor that you want.For example you can have a flag and making it false the Thread just finish it's work and that's it Thread finished.

 new Thread(new Runnable(){
    public void run(){

    //example code
    while(flag==true){
     System.out.println("Yeah i am true "); 
     //Thread.sleep(200); //Makes The Thread sleep
    }

  }}).start();   //create and start by default

Here

public class Server{

  public Server(){ //constructor

    Thread client = ClientMethod("Alex");
    System.out.println("i am Client "+client.getName());
  }


  //Make a Thread for a specific Client
  public Thread ClientMethod(String clientName){

     Thread client = new Thread(new Runnable(){
        public void run(){

         //do someWork
        //Then finish

       }//end of run method
     });

    client.setName(clientName); //set the NameOfThread to clientName
    client.start(); //start it

   return client; //return the Thread of this specific Client(as Object)

  }


 //Main Method
  public static void main(String[] args){       
      new Server();                 
  }

}//End of Class [Server]
crAlexander
  • 376
  • 1
  • 2
  • 12
  • 3) in this case, the name would be..? – Day_Dreamer Mar 06 '15 at 15:08
  • assume your 2) code is in a loop that continuously created new runnable instance and then given to myThread to "run" it. then what you say implies that all runnables will run in different threads with the same name? – Day_Dreamer Mar 06 '15 at 15:18
  • @Day_Dreamer The Thread let's name it myThread has not to do with others Threads.If you run for example together Thread1,Thread2,Thread3,... they are separate Threads.A Thread ends when the code is into it has been finished(EXCEPT if you have infinity loops).You can access Thread via it's name (myThread1.start(),myThread1.sleep(),...) just let me know what is the problem.. – crAlexander Mar 06 '15 at 15:24
  • I have while(true) loop that everytome creates a new **Runnable** and then creates a new thread to run it,using:Thread t = new Thread(Server.this.clientThread); (clientThread impleaments Runnable). I'm afraid that now all those threads have the same name – Day_Dreamer Mar 06 '15 at 15:39
  • @Day_Dreamer what exactly you want to do? – crAlexander Mar 06 '15 at 15:40
  • I'm creating server to handle client requests. For now I just want to have the clients threads to be created with different names to identify them so there would be a way to access the threads inambiguously – Day_Dreamer Mar 06 '15 at 15:42
  • @Day_Dreamer see edited at the end The method will return you the name of the Client then you can pass it to an array or whatever you will choose and you can access it – crAlexander Mar 06 '15 at 15:47
  • does it work like this? you pass a string as a name to the object name – Day_Dreamer Mar 06 '15 at 15:52
  • This is a good answer, but it would be better if you'd used the word "delegate". The object that you give to the `Thread(Runnable r)` constructor becomes the Thread object's _delegate_. The difference between inheritance and delegation is the difference between saying, "A foo is a bar" and saying "a foo _has_ a bar." The latter form is a much more powerful tool, and programmers should get into the habit of using it. Probably the only reason why `Thread` has a public `run()` method is that delegation had not yet been named as a design pattern when Java first rolled out. – Solomon Slow Mar 06 '15 at 17:17
1

the documentation page here describes it best

  • There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.

  • The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started.

  • Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

To address the naming: the API clearly shows that the constructor for thread:

Thread(String name)

has an argument that enables you to name the thread.

as for the difference between the two: Thread implements runnable. Classes that are inteded to run code while they are active can choose to implement either runnable or extend thread. Extending thread gives you the added features that come with Thread while runnable does not.

MSB
  • 854
  • 7
  • 24
0

2) the overloaded c'tor:

Thread (null, target, gname)

starts a runnable and assign it the name gname

unless specificly naming the thread the Automatic name will be: "Thread-"+n, where n is an integer.

Day_Dreamer
  • 3,311
  • 7
  • 34
  • 61