It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to write a program that uses multiple threads. I need to use the run() method after creating my thread objects. This run method seems to be built in. However, I need to write it and I need it to run a loop every time it is called. Can anyone help me understand how to do this?
You can create a new Thread instance by passing an anonymous implementation of the Runnable interface and then use the start() method to start the thread execution. See below:
Thread t = new Thread(new Runnable() {
public void run() {
while (!stopped) {
// do something interesting here
}
}
});
t.start();
Look at:
Counting Semaphores
http://tutorials.jenkov.com/java-concurrency/semaphores.html#counting
It's absolutely normal that the run() method is built into the Thread class. This class is meant to provide basic infrastructure for any class in your application that will represent a thread of execution. Think of Thread as 'any thread in the world'. Now the right way to use it in your application is to provide your own class that inherits Thread. This is done using extends keyword or using an anonymous class, like in Dan's answer. Let's assume you have extended the Thread class and called your class TaskToRunInParallel.
The documentation says that Thread class is special -- if you inherit it (like we just did) and put some code in the run() method of your own class (TaskToRunInParallel in our case), this code will be executed in parallel to the rest of the application. All you need to do is to call start() on the object of the class TaskToRunInParallel.
This is why the run() method is built-in: it provides you a prototype method to override in your own classes. This way any piece of code that works with Thread objects will be able to work with your TaskToRunInParallel objects, or any other class that inherits from Thread. Really: it is guaranteed that all of them will have run() method inherited from Thread and it's safe for that piece of code to call it. The result of this invocation will always be different though: each class inheriting from Thread may override run() in its own way. This is called polymorphism and together with inheritance is one of the cornerstones of object-oriented programming.
It's surprising how many concepts are involved when you think about overriding run() method of Thread class. Good luck.
Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
When we can have class and method as static?
Anybody please help me with some example...
When you don't need a class instance to invoke that method. It means that method does not depend on any non-static members of the class
You can make a method static if it doesn't use any non-static members of the class.
You can make a class static if it only contains static members.
If a method doesn't change it's behaviour based on different objects of it's enclosing class. it can be marked static.
Check Math class. all of it's methods are static cause, their behaviour just depends on the argument within methods and those methods don't make any change in the class states.
All the utility/helper methods can be (should be) marked as static. i.e. if their behaviour is same for all objects, why to have different copy for each object, just have one copy and let all objects share same copy.
You should check this also: Why are you not able to declare a class as static in Java?
A static method belongs to the Class and thus not to a specific instance. If you think at programming languages in term of message dispatching we can say procedural programming provides only 1 level of message dispatching as the name of the function correspond to its actual behavior. In Object Oriented Programming we have two level of message dispatching as you also has you have to specify an object plus the signature of a function (method). The same function may behave differently on different object depending on their status (subClass overridden method, etc.). A static method is instead like a global function you can execute where and how you want and always has the same behavior.
You may therefore limit the usage of static methods although there are cases in which they are helpful. In the Singleton pattern (http://it.wikipedia.org/wiki/Singleton) a static method is necessary to retrieve the Singleton's instance (also a private static attribute is necessary to keep track of it).
For those who claim Singleton are evil and you should always use Dependency Injection via Google Guice, also Guice relies on static method for instance to create an injector (http://lowcoupling.wordpress.com/2012/12/05/dependency-injection/).
So I guess the best answer is you should always think if the problem you are facing might just be solved by the injection of object but there are cases in which the usage of static methods is pretty reasonable.
I am going through Hello Android (Android PDF/tutorial) and have now seen this syntax a couple of times. Can someone please explain to me what Java syntax is used when run Runnable is defined?
private class AndroidBridge {
public void callAndroid(final String arg) { // must be final
handler.post(new Runnable() {
public void run() {
Log.d(TAG, "callAndroid(" + arg + ")" );
textView.setText(arg);
}
...
Is the code defining a Runnable object and overriding it's run method?
As Dave Newton indicated, this is an anonymous inner class implementing the Runnable interface.
As to why one would want to use this, it could be thought of as syntactic sugar of sorts. You'll notice that in your example, the code in run() has access to the same scope as where the anonymous inner class itself is defined.
This simplifies access to those members, as if you defined the class externally, you'd have to pass in a reference to any object whose members you wanted to invoke/use.
In fact, IIRC, this is actually what happens when Java compiles the anonymous inner class; if there are references to the outer containing class, the compiler will create a constructor that passes in a reference to the outer containing class.
The .post method expects a Runnable object, which in your code sample is declared anonymously and passed as the argument.
That will start a new thread for some long-running process.
The thread constructor needs a Runnable object, which has a run method that's called when the thread is ready.
When many Java apps start, all of the operations pile up on one thread, including the UI. I mainly use threads to avoid freezing up the UI if I'm doing something "heavy".
You've seen this happen when you click "execute" or something, and the UI suddenly is less than responsive. This is because the current thread doesn't have enough resources to build the UI and do whatever "execute" is asking.
So, sometimes that's done elsewhere, on a different thread, which needs a Runnable object.
It's worth noting that multithreading (where you make more than one thread on purpose) is notoriously difficult to work with, for debugging reasons mostly, IMO. But it is a useful tool, of course.
The code is defining an anonymous inner class that implements the Runnable interface, and implementing the run method to perform the appropriate actions.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
The community reviewed whether to reopen this question 5 months ago and left it closed:
Original close reason(s) were not resolved
What is "runnable" in Java, in layman's terms? I am an AP programming student in high school, whose assignment is to do research, or seek out from others what "runnable" is (we are just getting into OOP, and haven't touched threads yet).
A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.
The Runnable Interface requires of the class to implement the method run() like so:
public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
And then use it like this:
Thread t = new Thread(new MyRunnableTask());
t.start();
If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.
Advanced: Anonymous Type
Note that you do not need to define a class as usual, you can do all of that inline:
Thread t = new Thread(new Runnable() {
public void run() {
// stuff here
}
});
t.start();
This is similar to the above, only you don't create another named class.
Runnable is an interface defined as so:
interface Runnable {
public void run();
}
To make a class which uses it, just define the class as (public) class MyRunnable implements Runnable {
It can be used without even making a new Thread. It's basically your basic interface with a single method, run, that can be called.
If you make a new Thread with runnable as it's parameter, it will call the run method in a new Thread.
It should also be noted that Threads implement Runnable, and that is called when the new Thread is made (in the new thread). The default implementation just calls whatever Runnable you handed in the constructor, which is why you can just do new Thread(someRunnable) without overriding Thread's run method.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
Java provides two options to create a Thread class i.e either by implementing Runnable or by extending Thread class.
I know there can be many reasons to implement a Runnable but not sure where the scenario would be to extend a Thread class to create own Thread class?
Could you please provide me scenarios where extending Thread seems to be feasible or better option or advantageous...
There was a
Question on the threads but that did'nt answer my question
There is almost no reason to extend Thread, basically the only reason you would want to extend thread is if you were going to override things other than run() which is generally a bad idea. The reason it is less common to extend Thread is because then the class can't extend anything else, and if you're only overriding the run() method, then it would be kinda pointless to extend Thread and not implement Runnable.
Runnable is an interface with just one method run() that needs to be implemented by the class implementing the interface.
e.g.
public class MyRunnable implements Runnable {
#Override
public void run() {
//...
}
}
MyRunnable is not a Thread nor can you create a new thread just by using that class. So, it doesn't quite make sense to say -
Java provides two options to create a Thread class i.e either by implementing Runnable ...
You can extend the Thread class but just like #John said there isn't any point in doing so.
But if you want to execute some code in a new thread then the following is the best way -
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
t.start() method starts a new thread and invokes run() method on r (which is an instance of MyRunnable.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
This is very basic question, many of us didn't know this answer. In java, to call static methods we have to follow this classname.method();. But when comming to main(), its not been called by classname.main() even though it is static.
The best way to understand how "main()" is called by JVM is to see how "java" calls your main method. Here is the JNI example explaining the same.
mid = (*env)->GetStaticMethodID(env, cls, "main", "([Ljava/lang/String;)V");
...
(*env)->CallStaticVoidMethod(env, cls, mid, args);
Yes it is. The java "interpreter" takes the class name you're giving it, looks for a static main method taking a String array as argument and returning void, and calls this method. The java interpreter probably does this using native code, but that's not important.
If, inside a program, you want to call another class's main method, you can. main methods are not special in this regard. The only special thing they have is that they can be the entry point for the java interpreter.
The main method is invoked by the java interpreter itself when you run the class, without have to add the class names.
you can find more detail explaination # Why is the Java main method static?
You can call static methods in Java as though they were instance methods but this is considered bad practice.
public class Foo {
public static void bar() { ... }
}
...
Foo foo = ...
foo.bar(); // this will work
Foo.bar(); // but this is better
It's being called with Class.main() as you have to provide the class containing a main() method, when starting an application.
But when comming to main(), its not been called by classname.main() even though it is static.
How can you say so? I am afraid you have got it wrong.
You can call a static method using object,though.
Usually you never call main yourself.It is an entry-point for your program and JVM calls it to start the execution of the program.
Also this is the reason you need to pass the name of the class when you execute your code.
Remember this:
java ClassName
This is how you execute your program from command line. ClassName here is the name of your Class having the main method.
This class name is used by JVM to call your main method e.g, ClassName.main()And all this calling stuff is done using native code C/C++.You might want to google it, in case you want to know exactly how all this works.If this is not exactly what you were looking for, maybe you can explain the question little more.
Hope this helps.