writing Thread in Java - java

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?

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]

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.

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.

Related

Is any other possibility to create threads, tasks in Java which not extend Thread or implement Runnable, Callable<V>?

I know three ways of creation threads, tasks in Java. In job interview one guy asked me if it is possible to create thread in Java in other way. Is it is possible? If is, please put some example.
The only way to create a thread in Java is by creating a Thread object and starting it.
Quoting java language specification:
The only way for a user to create a thread is to create an object of this class; each thread is associated with such an object. A thread will start when the start() method is invoked on the corresponding Thread object.
Runnable and Callable are two interfaces that the JDK uses for submitting code to be executed in threads. For example, in its various java.util.concurrent classes.
Runnable, by convention, is an interface accepted for arguments to Thread's constructor. You can extend Thread so that constructors of child class accept any other type of argument. Similary, Callable is accepted by thread pools in java.util.concurrent. You can develop other kinds of thread pools, which accept any other types of tasks.
Creating a thread anonymously. For example as given below :
import java.util.Date;
class TestDemo
{
public static void main(String[] args)
{
Thread t = new Thread()
{
public void run()
{
while(true)
{
System.out.println(new Date());
try
{
Thread.sleep(1000);
}catch(Exception e){}
}
}
};
t.start();
}
}

What's the difference between different ways to start a thread?

I have a class named MyThread which extends the Thread class and implement the run() function.When I want to run it , I got two ways:
new a instance and call the function,like: new MyThread().start()
new a instance and transmit the instance to the construction function of Thread as a parameter and then call the start function of Thread. Like this: (new Thread(new MyThread)).start();
Anybody can just tell the difference?
Because you've said your class extends Thread, the second one is a bit redundant. In your second example, you're not using your class as a Thread, you're just using it as a Runnable.
Normally, you'd either extend Thread and then call its own start (your #1), or you'd implement Runnable and then use a Thread to run it (your #2). But you wouldn't extend Thread and then use another Thread to run it.
In terms of what's different, if you need to do anything to control or interrogate the thread, in your first case you'd use the Thread methods on the instance of your class; in the second case, you'd use them on the instance you create with new Thread. If you extend Thread but run it via #2, the Thread methods on your instance are irrelevant and could be confusing.
That last bit is probably clearer with examples:
Example of extending Thread:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Start it
foo.start();
// Wait for it to finish (for example)
foo.join();
Note we started and joined the thread via the foo reference.
Example of implementing Runnable:
class Foo implements Runnable {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it
Thread thread = new Thread(foo);
// Start it
thread.start();
// Wait for it to finish (for example)
thread.join();
Note we started and joined the thread via the thread reference.
Don't do this:
class Foo extends Thread {
public void run() {
// ...
}
}
// Create it
Foo foo = new Foo();
// Create a Thread to run it -- DON'T do this
Thread thread = new Thread(foo);
// Start it
thread.start();
...because now you have Thread#join available on both foo and thread; which is the right one to use? (The answer is: The one on thread, but it's confusing, so it's best not to do that.)
Well, you have two method to implement a multi-thread.
extend Thread and use new MyThreand().start() to start your thread.
implement Runnable interface. In this condition, you can use (new Thread(new MyThread)).start(); to start a thread.
For detailed infomation, just refer to oracle official doc.
The MyThread instance you are passing is just acting as Runnable and not as a separate Thread.
There is basically no difference logically in both ways:
What Thread internally does on start() is, calls the run() method of Runnable.
And when you are doing new Thread(new MyThread()).start(), you are just being redundant as Thread itself implements Runnable.
But it will make no difference logically as the run() method of MyThread will be called by the new Thread.
You shouldn't do this. Creating a thread does change some variables like the "number of unstarted threads" in ThreadGroup.
While it shouldn't exactly cause problems, it's bad style and will confuse people ("Why did he do that? There must be a good reason!").
If your class itself extends Thread you can follow your first way:
MyThread myThread = new MyThread();
myThread.start();
If you look into the JavaDoc, you'll see that your second way is targeted towards classes that (just) implement Runnable (which means that your class just needs to implement run() method).
public class MyClass implements Runnable {
public void run() { ... }
}
Thread thread = new Thread(new MyClass());
thread.start();
The difference is that Runnable is only an interface whereas Thread is a class. This means that if you want to have your logic as part of a class which needs for some reason to extend a different class, then you can still implement Runnable and use the second way.
Thread itself is an implementation of Runnable. When create an instance of Thread and start it, it will executes it's own run() method. If non-null Runnable target is given to it's constructor, then it will invoke it's target's run() method as is evident from the implemented run() method of Thread class:
#Override
public void run() {
if (target != null) {
target.run();
}
}
The two ways to create a new thread of execution:
First one is to declare a class(i.e. PThread) to be a subclass of Thread: PThread extends PThread and should override the run method of class Thread. We can then easily create instantiate of this class and invoke start() on it:
PThread pThread = new PThread(args);
pThread.start();
Second one is to declare a class that implements the Runnable interface: RThread implements Runnable then implements the run method. We will have to instantiate the RThread and pass it to a Thread instance as a Runnable target:
RunThread rThread = new RunThread(args); // args constructor argument if required
Thread t = new Thread(rThread);
t.start();
As you have seen from the above way to start a thread, It is actually allowed a class extending a Thread, such as PThread to be passed to a new Thread constructor as a Runnable target to start it. Because Thread itself is an implementation of Runnable.
PThread pThread = new PThread(args);
Thread t = new Thread(pThread);
// allowed as pThread is extending Thread and hence,
//an implementation of Runnable
t.start();
But this operation is unnecessary or, rather you should not do it. As pThread is already a Thread, we could just call pThread.start() to executes it's run() method, which is the heart of a Thread. Creating another thread just to execute pThread is just extra overhead as it will not do anything other than executing pThread's run() method.
However, you should not actually use an extension of Thread at all. Because,
implementing Runnable is always preferable over extending a Thread:
Inheriting all Thread methods are additional overhead just for representing a Task which can can be done easily with Runnable.
Implementing Runnable to a Class still allows us to extend it to other class if necessary.
In OOP, extending a class generally means adding new functionality, modifying or improving behaviors. If we are not making any modification on Thread or changing it's behavior, than use Runnable interface instead.
Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
Executors, which makes life easier with multi-threading accepts Runnable as task.
Reference:
Class Thread
Difference between Thread class and Runnable interface
(new Thread(new MyThread)).start();
each Thread implements Runnable; in this case MyThread instance is used as Runnable the new thread calls the run method implemented by MyThread. You will not be able to stop the thread ( or control it by any means) by using MyThread.
There are absolutely no difference between how you start the Thread (class implementing Runnable or extending Thread class)
It's only the abstraction that you apply, note (Runnable object, is more general, because the Runnable object can subclass a class other than Thread) Good Coding Practice.
In both of the cases Thread.start() will called

Thread class empty constructor

I was wondering what's the reasoning of the existance of an empty constructor on Thread class.
Since you cant give it a Runnable when it's created, creating a Thread like this:
Thread t=new Thread();
Is completely useless.
Can you think of a reason why there is not an option of adding a runnable to a thread AFTER CREATION?
You can override the Thread class, too. Your own implementation could then do something sensible in the run() method without the need for a Runnable.
The following works:
new Thread() {
public void run() {
System.out.println("Well you can change the run method.");
}
}
but yes that's not what I'd consider good practice.
Thread class can be subclassed, and it's run() overriden. See the Javadoc.

Threads in java

How can I implement a run() method of thread if I create a Thread Global?
I mean If I create a Thread Globally then can I implement its run() method {" public void run()"} anywhere in my Application?
In the run() method I have to write the code to perform some action.
IF I can do it then please can anyone show me briefly how to do it particularly.
I am a bit confused!!!!!
Thanks,
david
Given the following class:
class MyWorker implements Runnable {
#Override
public void run() {
}
You can create and start a thread with:
Thread thread = new Thread(m_worker);
thread.setDaemon(true); // If the thread should not keep the process alive.
thread.setName( "MyThreadName" );
thread.start();
You can implement the Runnable as a top-level class, a nested class, or an anonymous class.
Multi-threaded programming requires special attention. Joshua Bloch's "Effective Java," 2nd ed., has an introduction to some issues in its "Concurrency" chapter. It would be worth reading. One suggestion is to prefer executors and tasks to raw threads.
A thread is represented by a Thread object. You create a Thread object as an anonymous inner class or by subclassing Thread with your own class that implements run(). Here is the anonymous version.
Thread t = new Thread() {
public void run() {
// Do something on another thread
}
}
Here is the subclass version
class MyThread extends Thread() {
public void run() {
// Do something on another thread
}
}
Thread t = new MyThread();
Typically you use an anonymous class for a quick and dirty operation and you create a subclass if the thread has a payload (parameters, result etc.)
Note that these snippets just declare the thread. To actually run the thread you must call start():
t.start();
That's it. When the thread starts, it invokes the run() on the new thread. The main thread and the new thread run in parallel.
More advanced topics like thread synchronisation should really be tackled when you've got the basics worked out.

Multiple threads in Java causing problems

Sorry for another vague example...but I have a single class where I'm starting a new thread instance. However, if I add a new thread instance, it interrupts (destroys?) the first.
But, if I run two instances of the class (separately, after I turn them into jar files) where each instance only opens up a single thread, they both run concurrently and fine.
I'm convinced the error is the way I'm implementing multi-threading.
Any suggestions for things to look for? Thanks! Sorry for the vague example.
You cannot assume that an arbitrary class is thread-safe.
Authors of a class should be explicit about the thread-safety of their classes, but it's very common that they do not. Given that environments such as Servlets may be intrinsically mulit-threaded this can be a real problem.
You need to study the class and discover which, if any, methods are thread safe. It is possible that the class InstanceOfClassIDontControl has static variables that are getting confused by multithreaded access. If you not only don't control the class, but can't even see its source then you are going to need the owners support.
Ok, here's an example:
public class driver {
public static void main(String args[])
{
Thread x;
Thread y;
x = new Thread(new pow());
y = new Thread(new pow());
x.start();
y.start();
}
}
public class pow extends Thread {
public void run() {
InstanceOfClassIDontControl a = new InstanceOfClassIDontControl();
a.doVariousProcesses();
}
}
In the example, I (obviously) don't control the class whose instance is created and called in the thread. Each thread may run for minutes. But whenever a concurrent thread is ran (in this case, with y.start()), it destroys the actions of the object called in the run() instance of x.start().

Categories

Resources