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.
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.
How to access the thread variable from outside of the thread , I have the hashmap inside the thread which I want to access from my main program or service.
public class Sample {
class Thread {
//private synchronized hashmap declared here
}
}
I want to access the hashmap declared in Thread in other class lets say Class Abc
The real problem with multiple threads accessing data is synchronization. If you have a map with data, make it a ConcurrentHashMap, and place it so that you can access it. Now you have access to the data in your map. Note that there could be other dependencies in your code that require more synchronization, but at least accessing the data in the map is safe.
Update: In your case I would do something like:
public class Sample {
Map mMyMap = new ConcurrentHashMap();
void foo() {
// Access from here
}
class Thread {
// And from here
}
}
You can make it private, but there is much to say about inner classes and private that is out of scope of this question.
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.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”
I have two questions about multithreaded programming. I read a few answers on the internet, but still I can't find a satisfying answer.
Implementing the Runnable is preferred over extending the thread class. Why?
How is it that we are able to get away with overriding just the run() method?
According to 'The Complete Reference to Java' by Herbert Schildt, If we are not overriding any methods of Thread class other than run(), it's better we implement Runnable.
My 2nd question might sound a bit silly, but I seem to be missing something and I'm not sure about how the whole thing works.
1: Implementing the Runnable is preferred over extending the thread class. why?
Because it allows your class to extend another class if it wants to instead of being forced to extend Thread.
2: How is it that we are able to get away with over-ridding just the run() method?
You can certainly override other methods but the Thread object will call the run() method when the thread is started. That's how it works. The default Thread.run() method is:
public void run() {
if (target != null) {
target.run();
}
}
If you call the Thread constructor with a Runnable then that is what the target is set to. If you instead extend Thread and #Override the run() method then that is the method that will be called when the thread object is started.
That's how the Thread class works.
2: How is it that we are able to get away with over-ridding just the run() method?
You may have misspoke here and were instead asking why we only need to implement the run() method in Runnable().
Runnable is an interface with a single run() method that you must implement.
Thread is a concrete class that you are extending. You can override any methods in a concrete class unless the class is final or the method is final.
Make sure you use proper Java terminology and don't mixup implement and override.
Three fundamentals before you delve deeper.
A class can only extend one class.
A class can implement any number of interfaces.
An interface can extend any number of interfaces.
Additionally, an abstract class is a class. So it behaves like a class and you can't implement it. You only extend it.
There are a number of traps which can occur if you extend Thread which you don't get with implementing Runnable.
public static String getName() {
return "My Test Application";
}
public static void stop() {
System.out.println("Shutting down");
}
public static void main(String... args) {
new Thread() {
#Override
public void run() {
System.out.println(getName());
stop();
}
}.run();
System.out.println("Bye now.");
}
prints
Thread-0
Bye now.
See how many bugs you can spot.
Unnecessary inheritance is generally a bad idea. You might hear "prefer composition over inheritance" often enough. I'm sure google can pull up enough links for you. The general issue is that inheritance bring tight, unnecessary coupling between classes.
Same goes for GUI components, btw.
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.
Right now I am confused with inheritance and object of class. We can do the same using object as inheritance does.
ok here is first code
public class MainForm {
GUI g = new GUI();
g.show();
g.destroy();
}
class GUI {
void show(){
......
}
void destroy (){
......
}
}
now second one
public class MainForm extends GUI {
//GUI g = new GUI();
void show();
void destroy();
}
class GUI {
void show(){
......
}
void destroy (){
......
}
}
both code do the same.Right? then
Why should I extend a class when i can do the same using an object of class?
Inheritance is often used when you want to create multiple classes of a parent class, without duplicating a lot of logic. I may have a class named Animal which has methods speak(), walk(), and sleep(). I also may want to have specific instances of Animal like Cat and Dog.
Rather than implementing all three of those methods individually, I can write them in Animal and then have my other classes extend Animal to make use of those, as well as add any methods specific to those classes (like claw() or fetch()).
The benefits are reduced code duplication and better 'abstraction' of the objects. However, there are some drawbacks as well, as this article points out. It is important to know when inheritance is useful, and when it is not.