Java - How to 'return' a value in a class -
i trying assign value or return value in class. this:
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; } } is possible? thanks!
it possible, need change code bit. check following classes:
the first 1 runnable, method need implement defined v call() throws exception, instead of void run(): allows return value.
the second 1 wraps callable<v> (or runnable plus constant return value), , runnable itself, can pass thread doing runnable.
so, change code following:
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 background thread has thrown exception"); e.getcause().printstacktrack(); } } class myclass implements callable<boolean> { @override public boolean call() throws exception { // let's fake long running computation: thread.sleep(1000); return true; } } the call ft.get() return after call() method finishes executing (on background thread), have wait 1 second before line gets printed console.
there many other useful methods on futuretask. check the documentation.
there other classes may find useful: executorservice , implementations, , factory methods in executors. has method called submit accepts runnable or callable<v>, , returns future<?> or future<v>, 1 of interfaces implemented futuretask. similar behaviour. example:
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 background thread has thrown exception"); e.getcause().printstacktrack(); } es.shutdown(); } the advantage of executorservice manage threads you. may create threads , reuse them callables , runnables submit: possibly improve performance if have many such jobs, since avoid creating 1 thread per job -- thread creation has overhead!
edit: .get() method throws executionexception, wraps exception might thrown during execution of .call() method. inspect exception, catch executionexception , call .getcause() on it. i've added missing try/catch block.
Comments
Post a Comment