Reputation: 7563
can you help me about java thread. I have two java class, my extends thread class have parameter, in MyMaster class how i get the variable "runBoolean" ?
public class MyMaster {
public static void main(String[] args) throws InterruptedException {
Thread[] threads = new Thread[2];
for(int i=1; i<=2; i++) {
threads[i-1] = new MyThread(i);
threads[i-1].join();
//what to do ?
}
}
}
public class MyThread extends Thread{
int myBil;
boolean runBoolean;
public MyThread(int bil) {
myBil = bil;
start();
}
@Override
public void run() {
try {
System.out.println(myBil);
runBoolean = true;
} catch (Exception e) {
runBoolean = false;
//what to do ?
}
}
}
Upvotes: 0
Views: 746
Reputation: 7081
If the thread array will be filled with MyThreads then we can define the array like that:
MyThread[] threads = new MyThread[2];
Then in your code you can do get the value like that:
System.out.println(threads[i-1].runBoolean);
I do have some more comments though. First of all your loop is a bit strange ;) I would change it to:
for(int i=0; i<2; i++) {
threads[i] = new MyThread(i);
threads[i].join();
System.out.println(threads[i].isRunBoolean()); //Add a getter for that
}
It's better to get used to using 0 as first index. And access properties through getters and setters:
public class MyThread extends Thread{
private int myBil;
private boolean runBoolean;
public boolean isRunBoolean() {
return runBoolean;
}
..... Class body continues here....
}
If you want to handle the exceptions thrown inside the Thread they must be RuntimeExceptions (otherwise they require you to catch them inside the thread). In this case you will need exceptionHandler and something like that:
Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable e) {
System.out.println("Exception: " + e);
}
};
for(int i=0; i<2; i++) {
threads[i] = new MyThread(i);
threads[i].setUncaughtExceptionHandler(exceptionHandler);
threads[i].join();
System.out.println(threads[i].isRunBoolean());
//what to do ?
}
And then in the thread
@Override
public void run() {
try {
System.out.println(myBil);
runBoolean = true;
} catch (Exception e) {
runBoolean = false;
throw new RuntimeException("this is a bad plan!");
}
}
This is a bad design though and you shouldn't have to do it. If you want to wait for result from the thread (instead of accessing its properties as shown above) then you should do it with a Callable and just wait for the answer.
Upvotes: 2
Reputation: 2208
To access an attribute from outside a class you could either make this attribute public
(not recommended) or create a getter method.
In your class MyThread add a mathod that just return the value of the attribute runBoolean
. This is called a getter cause it's abasically a method that allows to get the value of an attribute.
public boolean getRunBoolean() {
return runBoolean;
}
Upvotes: -1