|
App.java
Thread runnable1 = new Thread(new MyThreadRunnable(), "runnable1");
runnable1.setName(runnable1.getName());
runnable1.start();
MyThreadRunnable.java
public class MyThreadRunnable implements Runnable {
private String name;
public void setName(String name){
this.name=name;
}
public void run() {
System.out.println("Testing MyThreadRunnable"+" "+name);
}
}
Why does line 2 of App.java result in a 'null' for the name member of MyThreadRunnable? Is it not so that I just created a new Thread, passed a Runnable to it and gave it a name? Is it not supposed to be so that the name property should carry the value of Thread's getName()?
I don't understand.
|
|
|
|
|
Simply put you are addressing the Thread method not the MyThreadRunnable method. You could change your code thus and it would work as expected:
MyThreadRunnable runnable = new MyThreadRunnable();
Thread thread = new Thread(runnable, "runnable1");
runnable.setName(thread.getName());
thread.start();
Panic, Chaos, Destruction. My work here is done.
Drink. Get drunk. Fall over - P O'H
OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre
I cannot live by bread alone. Bacon and ketchup are needed as well. - Trollslayer
Have a bit more patience with newbies. Of course some of them act dumb - they're often *students*, for heaven's sake - Terry Pratchett
|
|
|
|
|
You've already set the name to the thread in the constructor itself. Why are you again setting the same.
This works fine. It probably will not return null.
You'll need to call setName() on MyRunnable object and not on Thread object. By the way, the setName() method in MyRunnable object is not at all a name for the thread. It might be just for printing purposes. Do you want it like that only?
Remove runnable1.setName(thread.getName()), try calling the setName() method in the class that you've written (MyRunnable).
It should work! Test once.
Gowtham Gutha (http://java-demos.blogspot.com)
|
|
|
|