有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (5) 个答案

  1. # 1 楼答案

    简单地说

    invoke Thread.start in order to start the new thread.

    如果直接调用run方法,那么它就像同一线程中的普通方法调用一样

    说明:

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

    参见Defining and Starting a ThreadaJava教程

    Read more...

  2. # 2 楼答案

    run()方法定义线程将执行的操作start()方法启动线程以执行由run方法实现的任务

    如果直接调用run方法,它将由调用者线程执行。但是,start方法会导致在新启动的线程中处理任务。在前一种情况下,调用线程等待run方法完成。另一方面,在后一种情况下,新创建的线程将异步执行,因此调用线程将继续其工作,而无需等待run方法的完成

  3. # 3 楼答案

    你需要知道线程可以有不同的状态。基于http://www.tutorialspoint.com/java/java_multithreading.htm,线程有5种状态

    • 新建-线程已创建并可以启动
    • runnable-线程正在执行
    • 等待-线程正在等待其他线程完成;其他线程必须通过调用共享锁上的notify方法来通知该线程它已完成
    • 定时等待-类似于等待,但线程将在一段时间后自动停止等待,而不等待其他线程的信号
    • 终止-线程完成了任务

    run方法只包含当线程工作时(当它处于可运行状态时)需要执行的代码

    start方法需要负责将威胁状态从new更改为runnable,这样它就可以开始工作并使用自己的资源(例如处理器时间)来执行run方法的代码

    当您调用yourThread.run()时,来自run方法的代码将由调用此方法的线程执行,但如果您使用yourThread.start(),则来自run方法的代码将使用yourThread的资源执行

    看看这个例子

    public static void main(String[] args) {
        System.out.println("main started");
    
        Thread t = new Thread(){
            public void run() {
                try {Thread.sleep(2000);} catch (InterruptedException consumeForNow) {}
                System.out.println("hello from run");
            };
        };
        t.run();
    
        System.out.println("main ended");
    }
    

    run方法中的代码将暂停运行它的线程两秒钟(因为Thread.sleep(2000);),以便您可以在两秒钟后看到hello from run

    现在输出是这样的

    main started
    hello from run
    main ended
    

    因为run方法中的代码是由main线程(处理public static void main(String[] args)方法的线程)执行的,也因为两秒钟的暂停部分

    hello from run
    main ended
    

    后来印刷的

    现在,如果将t.run()更改为t.start(),那么run方法中的代码将由t线程执行。你们将通过观察结果看到它,这将是

    main started
    main ended
    

    (来自主流)两秒钟后

    hello from run
    
  4. # 4 楼答案

    如果直接调用线程的run()方法,那么该方法中的代码将在调用run()方法的线程中运行。调用start()将创建一个新线程,并在新线程上执行run()方法中的代码

    简单地说,直接调用run()可能是一个错误,因为实际上并没有创建新线程

    请参阅以下链接以获取参考

    http://javarevisited.blogspot.co.uk/2012/03/difference-between-start-and-run-method.html

  5. # 5 楼答案

    When program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.

    • 每个线程在一个单独的调用堆栈中启动

    • 从主线程调用run()方法,run()方法进入当前调用堆栈,而不是新调用堆栈的开头

    请参阅What if we call run() method directly instead start() method?另请参阅Difference between start and run method in Thread