Unable to understand declaration - java

I have a code snippet as
public class ThreadStates {
private static Thread t1 = new Thread("T1") {
public void run() {
try {
sleep(2);
for (int i = 100; i > 0; i--) ;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
.......And rest of code follows.
What type of declation is step 1. I can see that we have no inherited Thread class in ThreadStates class, then why run() method declaration is coming. PLease clarify what is happening.

You have created an anonymous inner class which inherits from Thread (note the { directly following new Thread(). You are giving this class a run method, and storing it in t1.

It's called an anonymous inner class. When you say 'new Thread("T1") { ... }', you're effectively defining a new subclass of Thread.
Is this a variation of an anonymous inner class?
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

When you call a class that directly implements the Runnable class, you immediately inherit all the methods that said class does. Thread is one of the classes that implements Runnable and it makes you implement the run()method which is an abstract one.
That's why it shows the run()nethod there.

Related

Why can't the the run() method be static in Multi threading?

Am new to multi threading programming, when I declare the run() method as static its giving the compiler error as
"This static method cannot hide the instance method from Thread".
I didn't understand what that means, so please help me.
public class hello extends Thread {
public static synchronized void run() {
for(int i=0;i<1000;i++)
System.out.println(i);
}
public static void main(String[] args) {
hello t1 = new hello();
hello t2 = new hello();
t1.start();
t2.start();
}
}
It is not necessarily relevent to multi-threaded programming, it is true of Java in general. If you have a class:
public class MySuperclass {
public void myMethod() {
//do stuff
}
}
You cannot then over-ride it to make it static:
public class MySubclass extends MySuperclass {
public static void myMethod() {
//do other stuff
}
}
This is not allowed.
That's what the error message means.
public void run();
is a Method declared in class Thread. As it's not static in Thread you cannot "change" it into a static method in your subclass. And given your example, you don't even need to do that.
If you need to have the code executed inside the Thread public and static and synchronized, I'd advise to refactor that part out:
#Override
public void run() {
staticRun();
}
public static synchronized void staticRun() {
for(int i=0;i<1000;i++)
System.out.println(i);
}
In the main() method you create two instances of Thread - t1 and t2 and then you call start() on them and that is correct you cannot run/start the class but an instance. That is why run() method is not supposed to be static. It needs an object (a Thread object) to be executed. Just remove static from your declaration and it shall be almost fine. Other thing is that you dont need to make your run method synchronized (it is counter productive - you use thread to execute in paralel and ynchronize only on specific parts never whole run method).
The instance method run() is already available in hello class due to inheritance. You are trying to create another method (static) with same name which is run().
If the method is not static, it will automatically override the implementation and hide the method instance of parent class..
So, is the Error.. Simple!
Because java is Object Oriented language and anything is java is object.
And task which you are trying to perform in multiple threads is object too and you should create this object. When object is created you should call start() method which is defined on Thread class. So to implement your own logic, you should override this behavior by implementing run() method in Hello subclass.
Run method defines logic which should be performed in other thread (note, that run method doesn't create new thread)
Start method tells java to create new native thread and perform your run method in this new thread
Try:
public class Hello extends Thread{
public void run()
{
for(int i=0;i<1000;i++)
System.out.println(i);
}
}
public class Main
{
public static void main(String[] args)
{
Hello hello t1 = new hello();
Hello hello t2 = new hello();
t1.start();
t2.start();
}
}
The thread Class has a run method, therefore if you define it again in the hello class then you are overriding it, (direct inheritance since Hello extends Thread) now, it makes no sense to turn a Object method into a Class method, (run method belongs to an object and not to the class) that is the reason why your compiler is complaining with the message:
"...you can not This static method cannot hide the instance method
from Thread".
in other words, you are violating inheritance rules with it.

Calling outerclass from innerclass with a thread in MVC

I am using a MVC model and am trying to create a thread in the controller. When I am in the inner class run() I need to get the correct model but it is throwing a null pointer.
Here is the code to create the inner class and thread from the outer controller:
Thread thread = new Thread(new runWithThread(OpsSec, AmToChange, AgentID, balance, currency, selected_account_obj));
thread.start();
Inside the runWithThread I try to get the correct Model. AMModel is the Model class and withdraw is a method inside it. getModel is defined in the abstract controller I am extending(implementation inheritance).
((AMModel)getModel()).withdraw(10, "USD");
It works in the outer class but not in the inner class and I am not sure why I am getting the null pointer with the ((AMModel)getModel()). Any help would be appreciated.
Thanks
I realized the error. I had "extends AbstractController" in both the controller outer class and in runWithThread inner class. I am using Rational Arch and it didn't flag anything so I didn't notice the error.
I know this is pretty old, but try AMModel.this.withdraw(10, "USD");. Here's a generic example:
class Outer
{
class Inner
{
public void test()
{
Outer.this.variable = 1;
}
}
public int variable = 0;
private Inner inner;
}
After calling inner.test(), variable would be 1.

Declaring Anonymous Inner class

rb.addActionListener(new ActionEvent(ae) {
public void actionPerformed(ActionEvent ae) {
nowCall(ae);
}
});
Another way
Thread th=new Thread(Runnable r) {
public void run() {
// do something
}
};
// notice the ending of above 2 snippets
I am really confused seeing these two.It seems there is no exact pattern to declare an anonymous inner class.
please explain the syntax for anonymous inner class.
The second isn't valid, as far as I can see and test.
What would be more common would be to create a new Runnable implementation:
Thread th=new Thread(new Runnable() {
#Override
public void run() {
// This implements Runnable.run
}
});
Now you could just override the run method of a normal thread:
Thread th=new Thread() {
#Override
public void run() {
// This overrides Thread.run
}
};
... but personally I prefer specifying the Runnable separately when creating a thread.
Now the difference that you noticed at the end is simply whether the expression is used as an argument (e.g. to the addActionListener method or the Thread(Runnable) constructor, or whether it's just assigned directly to the variable. Think of the whole new TypeName() { ... } as a single expression, and it's just the difference between:
Thread th = expression;
and
Thread th = new Runnable(expression);
There is the difference that in the first case your passing it as an parameter to a method and in the second example you're storing it in a local variable.
So you can't really compare both examples against each other.
[...] notice the ending of above 2 snippets
The trailing ) in your first example is simply a termination of
rb.addActionListener(
(i.e., your two examples have different endings because one is a right hand side of an assignment
Thread th = ... ;
and the other is an argument to a method call
...addActionListener( ... );
The syntax of creating an anonymous class is simply:
new SomeClassOrInterface() {
// implementation goes here
}
Which as you can see is the pattern for both of your examples.
From Anonymous Classes (Java in a Nutshell):
3.12.3. New Syntax for Anonymous Classes
We've already seen examples of the syntax for defining and instantiating an anonymous class. We can express that syntax more formally as:
new class-name ( [ argument-list ] ) { class-body }
or:
new interface-name () { class-body }
Also, you have a typo in your second example. It should probably read new Thread() { ... or new Thread(r) { ... (though in the latter case the overridden method will not be called).
Instanciating new anonymous class and passing the object to addActionListener method.
Instanciating new anonymous class and assigning the object to local variable th
They are both the same. You put the anonymous class right after the declaration, before the semicolons:
new ActionEvent(ae) {class details, methods etc} ;
and
Thread(Runnable r) { public void run() { // do something }} ;
in both cases you create a new instance of the class, in the first example you use it as a parameter to method, and in the second you assign it to a variable.
The difference is that you can either implement an interface as an anonymous inner class or extend a class. In you example both are extending a class

Java Runnable Question

I'm currently taking a course in Java and I've run into some confusing code.
Example:
Runnable runnable = new Runnable()
{
public void run()
{
//doStuff
}
};
I don't really get what this code is doing.
How can the run method be associated with an instance of a class?
I googled "Runnable" and found out that it is an interface. Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ?
I could use some links/explanations. Thank you!
It's an anonymous inner class that's implementing the interface Runnable. Yes, you can implement any interface this way, although there are reasons why you would or wouldn't in any given case (lack of reusability being a big one in the "wouldn't" column). More about anonymous classes here, but it's basically a convenient form of this:
// Define it
class Foo implements Runnable
{
public void run()
{
// Do stuff
}
}
// And then use it
Runnable runnable = new Foo();
...provided Foo is an inner (or "nested") class. More about nested classes here.
yes, you are implementing the interface by declaring the run. Yes it can be done for any interface.
This is typically done when you pass an implementation to a method that expects an argument of an Interface type, and you don't have a declared class that is appropriate. You can just implement the interface on the spot, and that code runs. Pretty neat.
I googled "Runnable" and found out
that it is an interface. Am I
implementing the interface by
declaring the run method between curly
brackets ? Can this be done for any
interface in java ?
Yes!
This code is instantiating an object which implements Runnable. Because we can't actually construct an interface, any code which attempts to do so must provide implementations for the interface's methods in curly brackets. We don't really get to see what class Java is creating to implement Runnable (these are abstract terms).
If you were to do the following:
Runnable runnable = new Runnable()
{
public void run()
{
System.out.println("I'm running");
}
};
runnable.run();
you would see "I'm running" as your output.
In some situation , this sample code will be useful .... test runna = new test()
class test implements Runnable{
test(){
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("asd");
}
}
}

Java, alert parent on object change

I have the following setup in Java,
public class Main {
// starts sub class
SubClass sub = new SubClass();
sub.start();
// sub will keep running and call method alert() on a specif change
// method alert is void but updates a public variable named status on sub
while(1==1) {
// I should ideally be able to catch/read sub status result here
// how can I do it?
}
}
I'm new to Java so this may not be valid and my approach may be wrong. That being the case please point me in the right direction.
Thank you.
I presume SubClass.start() starts a new thread so the parent runs in parallel with the child. Then the main class can do a Object.wait() on the sub object, and the SubClass thread can do a Object.notify() on the sub object.
you should start by putting your code into a main method :)
If your SubClass is not already a Runnable,
public class Main
{
public static void main(String args[])
{
Thread myThread = new Thread(new Runnable()
{
public void run()
{
//Instantiate your SubClass here and do stuff. You can pass yourself as a parameter if you plan to do callbacks.
}
});
myThread.setDaemon(true);
myThread.start();
}
}
Alternatively if you've implemented the Runnable interface on SubClass then just use the thread mechanics (wait(), notify(), etc etc).

Categories