Thread start()和Runnable run()之间的区别是什么? [英] What's the difference between Thread start() and Runnable run()

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

问题描述

假设我们有这两个Runnable:

Say we have these two Runnables:

class R1 implements Runnable {
    public void run() { … }
    …
}

class R2 implements Runnable {
    public void run() { … }
    …
}

这之间有什么区别:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();

    r1.run();
    r2.run();
}

而且:

public static void main() {
    R1 r1 = new R1();
    R2 r2 = new R2();
    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);

    t1.start();
    t2.start();
}


推荐答案

没有多个主题。两者都在单个(现有)线程中执行。没有线程创建。

First example: No multiple threads. Both execute in single (existing) thread. No thread creation.

R1 r1 = new R1();
R2 r2 = new R2();

r1 r2 只是实现 Runnable 接口的类的两个不同对象,它们具有 run()方法。当你调用 r1.run()时,你正在当前线程中执行它。

r1 and r2 are just two different objects of the class that implements the Runnable interfaces which have that run() method. When you call r1.run() you are executing it in the current thread.

两个单独的线程。

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);

t1 t2 是类 Thread 的对象。当你调用 t1.start()时,它会启动一个新的线程并调用 run() c $ c> r1 以在该新线程内执行。

t1 and t2 are the objects of the class Thread. When you call t1.start(), it starts a new thread and calls the run() method of r1 internally to execute it within that new thread.

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

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