Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

thread start does not call run

I am confounded with a strange issue. Basically the situation is like this. I implemented the runnable in my class, I pass the class in a new thread, I override my run() method within the class that implements runnable and then I start the thread. However, my start() method never calls my run() method. I've search the forums but I can't seem to find another similar problem.

Below is my sample code:

public class EmailManager implements Runnable {
    PortalManagementSBLocal pmbr= this.lookupPortalManagementSB();
    Thread runner;
    String emailServerName = "";
    String smtpPort = "";
    String emailTo = "";
    String emailFrom = "";
    String mailer = "JavaMailer";
    String subject = "";
    String message = "";

    public EmailManager() {
    }//default constructor

    public EmailManager(String emailTo, String subject, String message){

        this.emailTo=emailTo;
        this.subject = subject;
        this.message = message;
        //need to make this dynamic
        this.emailFrom = pmbr.getEmailFrom();
        this.emailServerName = pmbr.getEmailServerName();
        this.smtpPort = pmbr.getEmailSMTPPort();
        //runner = new Thread(this,"Email");
        runner = new Thread(this);
        runner.start();
        System.out.println("***** Email Thread running...");


    }

    @Override
    public void run(){
        sendEmail(); //This is never called
    }

Would really appreciate any guidance! Thanks a ton!

like image 645
Qin Zhengquan Avatar asked Jun 20 '12 12:06

Qin Zhengquan


3 Answers

How do you know that this method is never called?

The simple test below works. So there's no problem creating a thread and running it from within the constructor. So there's something else going on that's preventing you from seeing that sendEmail() is being called.

public class Test implements Runnable {
  Thread runner;
  public Test() {
    this.runner = new Thread(this);
    this.runner.start();
  }

  @Override
  public void run() {
    System.out.println("ya");   
  }

  public static void main(String[] args) {
    new Test();
  }
}
like image 156
Erick Robertson Avatar answered Oct 15 '22 18:10

Erick Robertson


i think, the problem is that you're passing this before the constructor call is complete. This might help you: https://stackoverflow.com/a/5623327/1441485

like image 36
iozee Avatar answered Oct 15 '22 18:10

iozee


dont use runner = new Thread(this); in a constructor

move "runner = new Thread(this); runner.start();

to init function, create instance using new and call this init()

like image 36
Subin Sebastian Avatar answered Oct 15 '22 19:10

Subin Sebastian