Thread start() 和 Runnable run() 有什么区别 [英] What's the difference between Thread start() and Runnable run()

查看:63
本文介绍了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() { … }
    …
}

那么这两者有什么区别:

Then what's the difference between this:

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();

r1r2 只是两个不同的类对象,它们实现了 Runnable 接口,从而实现了 run()方法.当您调用 r1.run() 时,您正在当前线程中执行它.

r1 and r2 are just two different objects of classes that implement the Runnable interface and thus implement the 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);

t1t2Thread.当您调用 t1.start() 时,它会启动一个新线程并在内部调用 r1run() 方法以在该线程内执行它新线程.

t1 and t2 are 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天全站免登陆