简体   繁体   English

一次创建多个Java线程

[英]Create multiple Java Threads at once

Is there any possibility to create the threads as follows, 是否可以按以下方式创建线程,

Thread odjhygThread= new Thread(objJob1, objJob2);

I think we couldn't, if we want to create what needs to be done? 我想我们不能,如果我们想创造需要做的事情? anyone knows the answer? 有人知道答案吗? Thanks in advance. 提前致谢。

A Thread runs one job. 线程运行一项工作。 That's the way they are designed. 这就是他们的设计方式。

If you are trying to run two jobs, use two Threads. 如果要运行两个作业,请使用两个线程。

If you want to hand over two jobs to be run in the background, read the JavaDocs for the Executors class, and the ThreadPoolExecutor class. 如果要移交两个要在后台运行的作业,请阅读Executors类的JavaDocs和ThreadPoolExecutor类。 It will take you a while to get your head around them, but unfortunately that's the nature of multi-threading in Java. 花费一些时间来解决这些问题,但是不幸的是,这是Java多线程的本质。 Complicated. 复杂。

我不确定这不是您的目标,但是..创建一个扩展Thread的类,并为其提供一个带有2个参数的c'tor。

Yes (unless I am missing something here) 是的(除非我在这里丢失了一些东西)

public class MyThread extends Thread {
    private final Object object1;
    private final Object object2;

    public MyThread(Object o1, Object o2) {
        //implicate call to super()
        object1 = o1;
        object2 = o2;
    }
    @Override
    public void run() {
        //ha ha
        //he he
        //ho ho
        //off to work we go
    }
}

I assume you're already aware of the Thread constructor that takes a Runnable as an argument. 我假设您已经意识到使用Runnable作为参数的Thread构造函数。 Are you trying to create a thread that calls run() on two different Runnable objects? 您是否要创建一个在两个不同的Runnable对象上调用run()的线程? This doesn't exist, but it would be easy to write: 这不存在,但是很容易编写:

public class RunTwoThings implements Runnable {

  private Runnalbe thing1;
  private Runnable thing2;

  public RunTwoThings(Runnable thing2, Runnable thing2) {
    this.thing1 = thing1;
    this.thing2 = thing2;
  }

  public void run() {
    thing1.run();
    thing2.run();
  }

}

You'd might want to do some exception handling to prevent problems in thing1 from preventing the execution of thing2. 您可能需要执行一些异常处理,以防止thing1中的问题阻止thing2的执行。 Then, just create a new thread like so: 然后,只需创建一个新线程,如下所示:

Thread odjhygThread= new Thread(new RunTwoThings(objJob1, objJob2));

If that's not what you're trying to do (eg if you want them both to run simultaneously in their own threads), you probably want Steve M.'s answer above. 如果这不是您要尝试执行的操作(例如,如果您希望它们都在各自的线程中同时运行),则可能需要Steve M.的回答。

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

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