【问题标题】:What will happen use run() instead of start() of a thread? [duplicate]使用 run() 而不是线程的 start() 会发生什么? [复制]
【发布时间】:2015-01-26 18:39:20
【问题描述】:

闲置线程类工作正常。我可以理解它的过程。然后我变了

mc.srart() 进入 mc.run() 但没有任何改变,也没有任何错误。

有人可以向我解释一下吗?我们可以一直使用 run() 而不是 start() 吗?

public class Main {

    public static void main(String[] args) {

        Myclass mc = new Myclass();
        mc.start();
    }
}

class Myclass extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.print(i + "--");
        }
    }
}

【问题讨论】:

  • t.start() 是库为您的代码提供调用以启动新线程的方法。 run() 是您的代码为库提供的用于调用 in 新线程的方法。 run() 方法是定义线程将做什么的方法。

标签: java multithreading java-threads


【解决方案1】:

直接在Thread 对象上调用run 会破坏首先拥有Thread 的意义。

如果您调用run,那么run 将在当前Thread 中执行,作为正常方法。您必须在 Thread 上调用 the startmethod 以使 run 在不同的 Thread 中执行。

使该线程开始执行; Java虚拟机调用该线程的run方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2016-05-03
    • 2011-08-06
    • 2012-05-17
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    相关资源
    最近更新 更多