通过调用start()和run()来运行Thread,有什么区别? [英] Running Thread by calling start() and run(), what is the difference?

查看:235
本文介绍了通过调用start()和run()来运行Thread,有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本问题,我对此感到困惑,

It may be a basic question, i was confused with this,

我喜欢这个文件:

public class MyThread extends Thread {
    @Override
    public void run() {
        //stuffs
    }
}

现在在另一个文件中我有这个:

now in another file i have this :

public class Test {
    public static void main(String[] args) {
        Thread obj = new MyThread();

        //now cases where i got confused
        //case 1
        obj.start();   //it makes the run() method run
        //case 2
        obj.run();     //it is also making run() method run
    }
}

那么在上面两种情况之间有什么区别,是情况1是创建一个新线程而情况2是不是创建一个线程?这是我的猜测...希望能更好地回答SO guys.Thanks

so in above what is the difference between two cases, is it case 1 is creating a new thread and case 2 is not creating a thread ? that's my guess...hope for better answer SO guys.Thanks

推荐答案

start() 在新线程中运行 run()中的代码。直接调用 run()不会在新线程中执行 run(),而是在线程从(。)调用run()

start() runs the code in run() in a new thread. Calling run() directly does not execute run() in a new thread, but rather the thread run() was called from.

如果你打电话给 run()直接,你不是线程。直接调用 run()将阻塞,直到 run()中的任何代码完成。 start()创建一个新线程,并且因为 run 中的代码正在该新线程中运行, start()立即返回。 (好吧,技术上不是立即,而是在创建新线程并将其踢掉之后。)

If you call run() directly, you're not threading. Calling run() directly will block until whatever code in run() completes. start() creates a new thread, and since the code in run is running in that new thread, start() returns immediately. (Well, technically not immediately, but rather after it's done creating the new thread and kicking it off.)

此外,你应该实现runnable,而不是扩展线程

这篇关于通过调用start()和run()来运行Thread,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆