Oku
Oku

Reputation: 71

Thread Logic in Methods

I need to understand how threads run inside methods, for example if i do this

The thread execute and everything its ok

private void someMethod()
{
    myThread obj = new myThread();
    obj.start();
}

private class myThread extends Thread {
     @Overrride
     public void run() { 
         // Actions 
     };
}

But if i do this the thread got triggered at last (after callAnotherMethod and that random variable declaration) even if i put the thread calling first

private void someMethod()
{
    myThread obj = new myThread();
    obj.start();

    callAnotherMethod();
    String someVariable = "";
}

private class myThread extends Thread {
     @Overrride
     public void run() { 
         // Actions 
     };
}

My problem its i need to make somethings in the thread to use after in my methods but if i write code this way, my thread got triggered at last. How can i use my thread first and then use another methods ?

Sorry about my english

Upvotes: 0

Views: 654

Answers (2)

hemant1900
hemant1900

Reputation: 1226

You can use Callable and Future classes. Callable is a thread which returns a Future object once its job is done. You can wait for the Future to become available. See the example from JavaDoc - http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html

Upvotes: 1

eduyayo
eduyayo

Reputation: 2038

if you need to execute in sequence... what´s the point on using another thread??

But if you´re running two heavyload operations, one in a background thread and one in current thread, you can call .join() and then continue...

Upvotes: 0

Related Questions