在一个简单易懂的解释中,什么是Java中的Runnable? [英] In a simple to understand explanation, what is Runnable in Java?

查看:666
本文介绍了在一个简单易懂的解释中,什么是Java中的Runnable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用外行人的话来说,Java中的runnable是什么?我是高中的AP编程学生,他的任务是做研究,或者从别人那里寻找runnable是什么(我们刚刚进入OOP,还没有接触过线程)。

What is "runnable" in Java, in layman's terms? I am an AP programming student in high school, whose assignment is to do research, or seek out from others what "runnable" is (we are just getting into OOP, and haven't touched threads yet).

推荐答案

Runnable基本上是一种类(Runnable是一个接口),可以放入一个线程,描述线程应该做什么。

A Runnable is basically a type of class (Runnable is an Interface) that can be put into a thread, describing what the thread is supposed to do.

Runnable Interface 要求类实现方法 run(),如下所示:

The Runnable Interface requires of the class to implement the method run() like so:

public class MyRunnableTask implements Runnable {
     public void run() {
         // do stuff here
     }
}

然后像这样使用它:

Thread t = new Thread(new MyRunnableTask());
t.start();

如果您没有 Runnable 界面,Thread类,负责在另一个线程中执行你的东西,没有承诺在你的类中找到 run()方法,所以你可以得到错误。这就是你需要实现界面的原因。

If you did not have the Runnable interface, the Thread class, which is responsible to execute your stuff in the other thread, would not have the promise to find a run() method in your class, so you could get errors. That is why you need to implement the interface.

请注意,你不需要要像往常一样定义一个类,你可以做所有内联:

Note that you do not need to define a class as usual, you can do all of that inline:

Thread t = new Thread(new Runnable() {
    public void run() {
        // stuff here
    }
});
t.start();

这与上面类似,只是你不创建另一个命名类。

This is similar to the above, only you don't create another named class.

这篇关于在一个简单易懂的解释中,什么是Java中的Runnable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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