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();
Related
This is a piece of code I am using as an example of how to run multiple threads:
import javax.swing.SwingUtilities;
public class ThreadDem {
//field
Runnable doRun;
//constructor
public ThreadDem(){
//instantiates a runnable object
doRun = new Runnable(){
//have to override the abstract method run of runnable and am
//declaring method here in this block statement
#Override
public void run() {
System.out.println("Hello from thread: "
+ Thread.currentThread());
}
};
}
public static void main (String[] args){
ThreadDem demo = new ThreadDem();
System.out.println("Hello this is from thread: " +
Thread.currentThread());
//I use the invokelater method to invoke the run method of do run on a
//seperate thread
SwingUtilities.invokeLater(demo.doRun);
}
}
I more or less just took it from the docs on runnable. However I am finding it hard to understand why it works like this. I am still new to OOP and don't really understand how I can instantiate an interface(runnable) and if indeed my runnable object is not a class how can I define it a method(run())... can someone please explain to me in simple terms step by step exactly what is happening in that constructor so I can make sense of the process? Thankyou!
What you have created is called an Anonimous class. The link contains the official tutorial which explains what it is, but in a nutshell - you created a one-off class implementing Runnable and instantiated an object of said class.
As a suggestion - Don't try to tackle multithreading before you grasp the basic concepts of the language like OOP and grammar.
In Java interfaces can not be instantiated, they are simply guidelines of what a method must implement in order to implement that interface. In order to instantiate a thread in Java it's best to use
public class ThreadDem extends Runnable (recommended)
or
public class ThreadDem extends Thread.
At that point you're required to implement a "public void run" method that overwrites the empty one from Runnable. At that point you can simply call run on any object of type ThreadDem.
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.
I am new to threads and while learning it i cant understand the following,
public class myClass
{
public static void main(String args[]) throws InterruptedException
{
String[] myString = {"Object","Classes","Static","Final"};
for(int i=0;i<myString.length;i++)
{
System.out.println(myString[i]);
Thread.sleep(2000);
}
}
}
How come I'm able to use thread method without extending Thread class?
sleep is a static method. It doesn't require an instance to be called.
There are only 2 ways to make a class/method 'threadable' in Java. Extending Thread or implementing Runnable. What you are doing there is Thread.sleep() which is simply saying sleep the current thread.
It is just a static method supplied by Thread and as you have discovered doesn't really have much to do with multithreading specifically. A static method means an object of the containing class does not need to be instantiated to invoke the method which is why you can call sleep() without extending Thread.
Read about static methods in the Java tutorial. Learn the basics of the language before playing with threads. Threads are a difficult thing to master, and if you don't know what a static method is, it's too early to start using them, IMHO.
Here you are using astatic member method of Thread class, that's why you are able to use the sleep() function without requiring an instance.
sleep() is a static method of the 'Thread' class. as you might know static methods are invoked directly by the sysntax
MyClass.myStaticMethod().
you don't need to instantiate a Thread object to call sleep() method.
I want to create one method and call the created Thread inside that method in my Android Application, I am new to Java as I had told before.
Can anybody giive me an example of how should I create a method and call a Thread inside that method!
Thanks,
david
I'm not sure I understand your question. You want to start a thread inside a method?
The simplest way is:
public void myMethod() {
new Thread().start();
}
How you might want to do something in this thread, which can be done this way:
public void myMethod() {
new Thread(new Runnable(){
public void run(){
// do something here...
}
}).start();
}
Of course these anonymous objects can be expanded into full-fledged ones.
I'm not sure if it's a duplicate of this question, as I've not done any work on Android. But my answer on there will explain how to run a method inside a thread.
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().