在一个简单易懂的解释中,什么是Java中的Runnable?

编程入门 行业动态 更新时间:2024-10-10 23:16:24
本文介绍了在一个简单易懂的解释中,什么是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?

本文发布于:2023-11-10 07:13:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:易懂   简单   Runnable   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!