简体   繁体   English

Java获取不同类的多个线程以同时运行

[英]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. 但是,在该类中显示“教授已开始1”,但第二个从不显示。 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 此代码永远不会调用您自己的run()方法,如果您的类实现了runnable接口,则应执行此操作

prof = new Thread(this)
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() : 您没有提供完整的Professor类,所以确切的解决方案可能有所不同,但是我要注意的重点是:创建Thread类的实例,然后调用.start()

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

Alas, the Thread class by itself does not do any thing when you call .start() on it. ,当您在其上调用.start()时, Thread类本身不会执行任何操作。 you need to tell it what is the action that you want it to carry out once it has been start() -ed. 您需要告诉它,一旦它被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. 那就是:创建一个Runnable实例,在其中您重写run()使其可以执行您想要的任何操作。 Then pass this instance of Runnable to the constructor of the Thread object you're creating. 然后将此Runnable实例传递给您正在创建的Thread对象的构造函数。 When you subsequently invoke .start() the run() method of that Runnable will get executed. 当您随后调用.start()run()Runnablerun()方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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