简体   繁体   中英

Java Get multiple threads of different classes to run concurrently

Im not sure exactly what the problem is but for some reason I cant get threads from two classes to run at the same time. I can get multiple threads from one class to run at the same time, but when I try to start another class nothing happens.

public professor(){
    prof = new Thread();
    prof.start();
    System.out.println("Prof has started1");
}

public void run(){
    try{
        System.out.println("Prof has started2");
        prof.sleep(600);
        //do more stuff
}
    catch(Exception e){
        System.out.println("Prof error");
    }

This is how I started my second class, the first one is started in the exact same way and runs fine. With this class however "Prof has started1" gets displayed, but the second one never does. Am I missing something?

I think this is the reason

prof = new Thread();
prof.start();

This code will never call your own run() method, if your class implements the runnable interface, you should do this

prof = new Thread()
prof.start()`

You don't provide the full delcartion the Professor class so the exact solution may vary but the main point that I see is this: you create an instance of the Thread class and then invoke .start() :

prof = new Thread();
prof.start()

Alas, the Thread class by itself does not do any thing when you call .start() on it. you need to tell it what is the action that you want it to carry out once it has been start() -ed. There are several ways to do so, but I will go with this:

public professor() {
  prof = new Thread(new Runnable() {
    public void run() {
      try {
        System.out.println("Prof has started2");
        Thread.currentThread().sleep(600);
        //do more stuff
      }
      catch(Exception e){
        System.out.println("Prof error");
      }
    }
  });
  prof.start();
  System.out.println("Prof has started1");
}

public void run() {
}

That is: create an instance of Runnable in which you override the run() such that it does whatever you want it to do. Then pass this instance of Runnable to the constructor of the Thread object you're creating. When you subsequently invoke .start() the run() method of that Runnable will get executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM