-1

I have a thread that is being run, and it connects to a web server, the code is on a different thread because I do not want the program to get stopped every time I call the code.

While in the thread, I need to call a method but I need it to be called from the main thread, not sure if there is any way to do this.

If I wasn't very clear (I'm pretty sure I wasn't xD) then here is some pseudo-code:

thread.start(){
    <do webcall stuff>
    <call method from main thread>
}
bernhardkiv
  • 437
  • 4
  • 21
  • 3
    You call a method on an object, not on a thread. If you need to call something from within another thread, things get tricky. What is the background information to your question, the context? If this functionality is absolutely needed, I suppose that you could create an event queue of some sort, perhaps one that accepts Runnables or Callables, and then iterate through the queue from the desired thread. – Hovercraft Full Of Eels Sep 25 '14 at 19:46

3 Answers3

0

Use a concept such as a boolean, then have your main thread "watch for a change":

"The good way to do it is to have the run() of the Thread guarded by a boolean variable and set it to true from the outside when you want to stop it, something like:" - JACK

How to stop a java thread gracefully?

Community
  • 1
  • 1
Petro
  • 3,069
  • 3
  • 25
  • 51
  • 3
    Using interrupt (and checking periodically for it) is preferred to rolling your own. – user949300 Sep 25 '14 at 19:49
  • 1
    @user949300 I have 1 doubt.How do you interrupt() a main thread from a child thread.Should I be passing the thread Object reference to my child thread or is there a better way? – Kumar Abhinav Sep 25 '14 at 19:59
0

A possible code can be the following:

Make sure you

  • use "volatile" to not have bad side effects with running between threads
  • use a ConcurentLinkedQueue where you add tasks you process in your parallel threads

 public class Program {

    volatile static ConcurrentLinkedQueue<MyData> _items = new ConcurrentLinkedQueue<MyData>();

    public static void main(String[] args) throws InterruptedException {
        Thread thr = new Thread(()->{

        System.out.println("Web service called");
        _items.add(new MyData()); });

        boolean exit = false;

        while(!exit) {

          while (!_items.isEmpty()) {

            MyData item = _items.poll();

           //do something with your data
        }
        Thread.sleep(200);
    }
}
Hovercraft Full Of Eels
  • 280,125
  • 25
  • 247
  • 360
Ciprian Khlud
  • 424
  • 3
  • 6
-1

If you say that you want to call a method from where this new thread spawned out of. Then pass that instance to your new Runnable implementation of the object on which you want to call the method. There is no way that you can direct main thread should call particular method.

You can spawn new thread and call the method you need, from that thread.

Sandeep Vaid
  • 1,347
  • 10
  • 7