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.
Related
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();
}
}
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();
So I have been reading a tutorial on Android development, and I have come across something that I have never seen during my Java developing (mainly school work):
Thread th = new Thread() {
public void run() {
if (iotdHandler == null) {
iotdHandler = new IotdHandler();
}
iotdHandler.processFeed(); resetDisplay(
iotdHandler.getTitle(),
iotdHandler.getDate(),
iotdHandler.getUrl(),
iotdHandler.getDescription());
dialog.dismiss();
}
};
th.start();
Now the book says extend thread, and I kind of understand what its doing, in a sense, but it doesn't follow the usual way to extend a normal class in java like so:
public Class Dog extends Animal...
and then you can follow on and override methods and such. But my question is, what is it actually doing in making a reference to new Thread object, but at the same time creating a method right after it, and what I assume is overriding some sort of method in the Thread class? Since I do not know what it is called, I can't really search for it, so I apologize for the obvious question if it is one. Any help would be much appreciated.
Revise your Java books :) It's called an anonymous inner class and was originally introduced to facilitate Java GUI development (with AWT/Swing). Since Android UI development follows many of the same patterns, it is used quite often in Android.
What it does is instantiating a class in place (without defining it in a separate file, etc.), overriding some of its methods (int this case run()). You can also implement an interface this by if you provide implementations for all of its methods.
first of all, that is nothing Android specific. You can extend the same way in "normal Java". The reason for doing an class extend like that is to reduce classes, when this "class extension" is needed only once. In your example it would be the same to write
public class MyThread extends Thread
{
#Override
public void run() {
[...]
}
};
and later on:
MyThread thread = new MyThread();
thread.start();
So the advantage is, that you don't need to implement a class and instantiate it later on.
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.
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().