• Post Reply Bookmark Topic Watch Topic
  • New Topic

stuck on a thread question

 
dale conn
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all i have this code




when i run this line in main

Threads t = new Threads( 1, getMethod( Threads.class, "myMethod", null ), null );

i want to get the result the method has returned using this line of code

Object result = t.getResult()

But null is returned. i need to wait until Threads t = new Threads( 1, getMethod( Threads.class, "myMethod", null ), null );
is finished before i run Object result = t.getResult(), but don't know how

Can anyone show me how i get the result returned to me

many thanks
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use a wait notify scheme. See Object.wait and Object.notify and Object.notifyAll. Or you can use Thread.join.

I notice also that you have not assigned anything to the variable _task.
 
Henry Wong
author
Sheriff
Posts: 22514
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone show me how i get the result returned to me


Take a gander at notifications. You will also need an understanding of synchronization as well, in order to use notifications optimally.

As a quick example (meaning this code could be written much better), you could modify your getResult() method to wait for the result like this...



On the other side, you just need to modify you code to send the notification after the result is set.



Henry
 
dale conn
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in my main() method i have this



If i do this



obj is null

i've added the code amendments but Object obj = t.getResult(); still returns null

thanks for nay help
 
dale conn
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i also added _timer.schedule( _task, seconds*1000); to the Thread()
 
dale conn
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i put

Thread.sleep(2000);

Object obj = t.getResult();

System.out.println(obj);

in main() obj returns the correct result
 
dale conn
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry figured it out - now got it working

many thanks for your help
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See also the Future interface and FutureTask. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!