你可以帮我解决一下java线程吗?我有两个java类,我的扩展线程类有参数,在MyMaster类中我怎么得到变量“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 ?
}
}
}
答案 0 :(得分:1)
如果线程数组将填充MyThreads,那么我们可以像这样定义数组:
MyThread[] threads = new MyThread[2];
然后在您的代码中,您可以获得类似的值:
System.out.println(threads[i-1].runBoolean);
我确实有一些评论。首先你的循环有点奇怪;)我会把它改为:
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
}
最好习惯使用0作为第一个索引。并通过getter和setter访问属性:
public class MyThread extends Thread{
private int myBil;
private boolean runBoolean;
public boolean isRunBoolean() {
return runBoolean;
}
..... Class body continues here....
}
如果你想处理Thread内部抛出的异常,它们必须是RuntimeExceptions(否则它们需要你在线程中捕获它们)。在这种情况下,您将需要exceptionHandler之类的东西:
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 ?
}
然后在线程中
@Override
public void run() {
try {
System.out.println(myBil);
runBoolean = true;
} catch (Exception e) {
runBoolean = false;
throw new RuntimeException("this is a bad plan!");
}
}
这是一个糟糕的设计,你不应该这样做。如果你想等待线程的结果(而不是如上所示访问它的属性),那么你应该使用Callable进行,然后等待答案。
答案 1 :(得分:0)
要从类外部访问属性,您可以创建此属性public
(不推荐)或创建getter方法。
在你的班级MyThread中添加一个只返回属性runBoolean
的值的mathod。这被称为getter,因为它是一种允许获取属性值的方法。
public boolean getRunBoolean() {
return runBoolean;
}