In Call the method of Java class which implements runnable after creating its thread object #RNJ proposed launching a Java Thread as
SomeClass sc = new SomeClass();
new Thread(sc).start();
in order to being able to call sc's methods from the current thread.
To me two questions arise from this:
How can sc's thread lifecycle methods be called in this construct (like stop())?
Is this really a good practice for thread instantiation when one wants to be able to call the remote methods or is there a more elegant/cleaner solution?
1) You can't, you need to keep a reference to the newly created Thread, but that is just matter of rearranging the code a little.
SomeClass sc = new SomeClass();
Thread thread = new Thread(sc);
thread.start();
2) In my personal opinion is always cleaner to have something that implements Runnable (it implies that can be run, anywhere, and it's just that... something that "runs") than to create something that extends Thread and overwrites the run method. If you do that you are implying your SomeClass is a Thread (which is a very bold assumption, you probably just want something that can be run and that's it, a thread sounds like a not-nice abstraction, tighlty coupled to an implementation.).
In the very end both solutions are the same, but Runnable one is more elegant... and flexible! If you decide to change your implementation in the future so each of your tasks are not run in a new thread but in a shared Executor or a ThreadPool... you won't need to change anything on your Someclass if it extended Runnable.
Executor executor = Executors.newCachedThreadPool();
...
...
SomeClass sc = new SomeClass();
executor.execute(sc);
Related
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.
I just started learning java and I ran into a slight road block involving threads. I have a static method that I would like to run in its own thread, is this possible? In python I know it would look something like this:
import thread;thread.start_new_thread( my_function, () );
And I know how to use threading with non-static methods by implementing Runnable or extending thread, but this is not what I am trying to do.
Have a Thread's run method call the static method:
new Thread(Call::yourStaticMethod).start();
The above would create a Static Method that executes in another Thread:
public static void yourStaticMethod() {
new Thread(new Runnable(){
// This happens inside a different Thread
}).start();
}
You need to create a new Thread.(As far as I understand)
Thread t = new Thread(){
#Override
public void run(){
method();
}
static void method(){// do stuff
}
}
//finally
t.start();
You can always make a class inside a method and pass more arguments to the thread.
You dont need to wrap Runnable with Thread. Use whichever you like, it is the same thing!
The fact that the method is static is of little importance here.
If the static method really does only use local variables, no object fields or methods, then it is thread-safe. If it accesses any object fields or methods, it may not be thread-safe, depending on what those fields or methods are used for, in other code.
You can either create a new thread inside of a static method or other stuff. It depends on what you want to do.
If you are using Java 8+, you can also use Java lambda expresions. Like this:
new Thread(()-> MyApp.myStaticMethod()).start();
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
I am just playing around with threads in java. I have a class which implements runnable.
public class MyThread implements Runnable{
private boolean finished;
//Other variables
public void run(){
//Thread code
}
}
My understanding is that each thread of type MyThread will have its own copy of member variables and writes to those member variables need not be synchronized. Is this assumption correct? If correct, access to what needs to be synchronized? Can someone care to give a outline or pseudo code.? Thanks.
Not necessarily. You could create multiple threads using the same instance of MyThread. For example:
MyThread x = new MyThread();
new Thread(x).start();
new Thread(x).start();
new Thread(x).start();
Now there will be three threads all running code in the same object.
I suggest you rename MyThread as it's not a thread - it's a task for a thread to perform. That makes it clearer (IMO).
Each MyThread instance is a new instance, just like normal classes and objects.
Variables of native types are copied. This means that changing the variable in one thread does nothing to the other thread. These do not have to be synchronized.
For objects their references are copied. This means that two threads may have a reference to the same object. If the two threads manipulate that object at the same time, this can go bad. Therefore, these accesses have to be synchronized.
The Really Big Index trail on concurrency is well worth a read (yes, it has examples).
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().