简体   繁体   English

java Thread类run()方法

[英]java Thread class run() method

Thread class has run method to implement the business logic that could be executed in parallel.But I want implement different business logics in a single run method and to run simultaneously.How to get this feature. Thread类有run方法来实现可以并行执行的业务逻辑。但是我希望在单个run方法中实现不同的业务逻辑并同时运行。如何获得此功能。

thanks 谢谢

That's right. 那就对了。 You implement (or override) the run -method of a Thread to do stuff in parallell, however, there is an important difference when calling run vs calling start . 你实现(或覆盖)一个Thread的run -method来做并行的东西,但是, 当调用run vs calling start有一个重要的区别

There is nothing special with the run method. run方法没有什么特别之处。 Calling run will behave just like any call to a regular method, and the control will not return to the caller until the run method has finished. 调用run行为就像对常规方法的任何调用一样,并且在run方法完成之前控件不会返回调用者。 The magic happens in start . 魔术发生在start When calling start the control is returned to the calling side immediately, and a new thread is spawned that has the run method as entry point. 当调用start ,控件立即返回到调用端,并生成一个以run方法为入口点的新线程。

So, for example, if you want to execute two tasks simultaneously in different threads, you do something like: 因此,例如,如果要在不同的线程中同时执行两个任务,则执行以下操作:

Thread t = new Thread() {
    public void run() {
        doTask1();
    }
};

// Spawn a new thread that doTask1. (don't call run here!)
t.start();
// Control returns immediately while thread t is busy with doTask1.

doTask2();

An example run: 示例运行:

    Thread t = new Thread() { 
        public void run() {
            try {
                Thread.sleep(1000);
                System.out.println("Slept for 1 second.");
            } catch (InterruptedException e) {
            }
        }
    };

    t.run();
    System.out.println("Returned from run.");

    t.start();
    System.out.println("Returned from start.");

Yields output 产量

                       (one second pause)
Slept for 1 second.
Returned from run.
Returned from start.
                       (one second pause)
Slept for 1 second.

I think that the best course of action would be to have two separate threads. 我认为最好的做法是拥有两个独立的线程。

You can (and probably should) write a new class that implements Runnable and inside it place your logic. 您可以(也可能应该)编写一个实现Runnable的新类,并在其中放置您的逻辑。 If there are common activities between the two business logics that you have to implement, you can use this class as a base class for the two "Runnables". 如果必须实现两个业务逻辑之间的共同活动,则可以将此类用作两个“Runnables”的基类。 Each Runnable should be spawned in a separate thread. 每个Runnable都应该在一个单独的线程中生成。

You can find very good reasoning for Thread vs. Runnable on this post: "implements Runnable" vs. "extends Thread" 你可以在这篇文章中找到Thread vs. Runnable非常好的推理: “implements Runnable”vs.“extends Thread”

使这个run方法用一个逻辑产生新线程,用另一个逻辑产生另一个线程。

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

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