Java-如何';返回';类中的值
我试图在类中赋值或返回值。大概是这样的:Java-如何';返回';类中的值,java,class,return,Java,Class,Return,我试图在类中赋值或返回值。大概是这样的: void setOff() { boolean onValue = true; Thread t = new Thread(new myClass(onValue)); System.out.println("On: " + onValue); } class myClass implements Runnable{ public boolean on; public myClass (boolean
void setOff() {
boolean onValue = true;
Thread t = new Thread(new myClass(onValue));
System.out.println("On: " + onValue);
}
class myClass implements Runnable{
public boolean on;
public myClass (boolean _on) {
on = _on
}
public run() {
on = false;
}
}
这样可能吗?谢谢 这是可能的,但您需要稍微更改代码。检查以下类别:
Runnable
,但您需要实现的方法定义为V call()抛出异常
,而不是void run()
:它允许您返回一个值
第二个包是可调用的
(或可运行的
加上一个常量返回值),它本身是可运行的
,因此您可以将它传递给线程
,就像您使用可运行的
一样
因此,您可以将代码更改为以下内容:
void setOff() {
final FutureTask<Boolean> ft = new FutureTask<Boolean>(new myClass());
new Thread(ft).start();
try {
System.out.println("The result is: " + ft.get());
} catch (ExecutionException e) {
System.err.println("A method executed on the background thread has thrown an exception");
e.getCause().printStackTrack();
}
}
class myClass implements Callable<Boolean> {
@Override public Boolean call() throws Exception {
// let's fake some long running computation:
Thread.sleep(1000);
return true;
}
}
这样做的好处是,将为您管理线程。它可能会创建一些线程,并将它们重新用于您提交的可调用和可运行程序:如果您有许多这样的作业,这可能会提高性能,因为您将避免每个作业创建一个线程——线程创建有一些开销
EDIT:
.get()
方法抛出一个ExecutionException
,它封装了在执行.call()
方法期间可能抛出的异常。要检查异常,捕获执行异常
并对其调用.getCause()
。我刚刚添加了缺少的try/catch块。您正在寻找按引用赋值行为吗?@011011\u 0101011\u 0101011泛型很好。你会喜欢仿制药的。好吧!谢谢你的例子,我会试试看!是的,泛型。。。它们是一种祝福和皮塔。
public static void main() {
final ExecutorService es = Executors.newCachedThreadPool();
final Future<Boolean> f = es.submit(new myClass());
try {
System.out.println("The result is: " + f.get());
} catch (ExecutionException e) {
System.err.println("A method executed on the background thread has thrown an exception");
e.getCause().printStackTrack();
}
es.shutdown();
}