java - 由于Thread.currentThread().run()而递归调用run方法

标签 java multithreading runnable

我是多线程新手,正在尝试清除我的基础知识。

public class SleepExample extends Thread {

private int counter = 0;

@Override
public void run() {

    try {
        counter++;
        System.out.println("Value of counter "+counter);
        System.out.println("Thread going in sleep "+Thread.currentThread().getName());
        Thread.currentThread().run();
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Thread out of sleep "+Thread.currentThread().getName());
}

public static void main(String[] args) {
    new SleepExample().start();
    new SleepExample().start();
    Test test = new  Test();
    Thread t = new Thread(test);
    t.start();
}
}

//another class implementing runnable

public class Test implements Runnable {

@Override
public void run() {
    System.out.println("In Test runnable method");

}

}

当我运行此代码时,我的 SleepExample 运行方法在下面的行之后递归地调用自身

Thread.currentThread().run();

对于属于 SleepExample 的线程(线程 -0、线程 -1)和 它转到线程 t 的 Test 类的 run 方法。

我无法理解 Thread.currentThread().run(); 的用法

附注- 我读了它的java文档,所以我实现了一个可运行的

最佳答案

I am unable to understand the usage of Thread.currentThread().run();

您不应该直接调用它。来自 Thread.start()您应该使用 start() 来调用 run(),就是这样。

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).

It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

你已经在 run() 中运行,所以你应该只在你能说出你为什么这样做的情况下才调用它,即使这样它看起来像一个错误或者很令人困惑,我会建议您改用循环。

When i run this code, my run method of SleepExample recursively call itself after below line

您有一个方法调用自身,因此您应该预料到会发生这种情况。在这方面,Thread 没有什么特别的。它就像方法中的任何其他递归调用一样。

关于java - 由于Thread.currentThread().run()而递归调用run方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36826022/

相关文章:

java - 推断aspectj方法中参数的类型

java - 如何修改类设计以使其线程安全

java - 使用 Java AtomicStampedReference 的算法可以被认为是非阻塞的吗?

java - DataInputStream读取不阻塞

java - 如何在Spring Batch中使用db实现多个Reader

选择 pthread 中的打印顺序

等待并行代码完成的java代码

java execturorService - 提交任务并捕获异常

java - 如何使用 Eclipse 中的资源从 Maven 项目创建可运行的 jar

java - 部署示例 spring boot 应用程序时的生命周期异常