Java线程:如何实现可运行的线程工作 [英] Java Threading: How does implementing runnable work for threading

查看:82
本文介绍了Java线程:如何实现可运行的线程工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解,如果您想进行线程化,则可以在Java中扩展线程或实现可运行到多线程的方式.但是,为什么要为Java线程实现接口呢?使Java线程工作的可运行接口的重要性是什么? Java的界面是否可以扩展?

I understand that if you want to thread you can either extend thread or implement runnable to multithread in java. But why do you have to implement an interface for java to thread? Whats the importances of the runnable interface that makes java threading work? Does Java's interface extend from something?

推荐答案

关于Runnable接口的唯一特别之处在于,它是Thread在其构造函数中所采用的.这只是一个普通的界面.

The only thing special about the Runnable interface is that it is what Thread takes in its constructor. It's just a plain-old interface.

与大多数接口一样,关键是要按照合同进行编程:您同意将要运行的代码放入Runnable#run()实现中,而Thread同意在另一个线程中运行该代码(当您使用它创建并启动Thread时.

As with most interfaces, the point is that you're programming to a contract: you agree to put the code you want to run in the Runnable#run() implementation, and Thread agrees to run that code in another thread (when you create and start a Thread with it).

实际上是Thread执行"多线程(因为它与本机系统交互). Runnable的实现只是放置要告诉Thread运行的代码的地方.

It's Thread that actually "does" the multithreading (in that it interacts with the native system). An implementation of Runnable is just where you put the code that you want to tell a Thread to run.

实际上,您可以实现Runnable并运行它,而无需使其在单独的线程中运行:

In fact, you can implement a Runnable and run it, without having it run in a separate thread:

Runnable someCode = new Runnable() {
    public void run() {
       System.out.println("I'm a runnable");
    }
};
someCode.run();

所以Runnable本身与多线程无关,它只是在将代码块封装到对象中时扩展的标准接口.

So Runnable itself doesn't have anything to do with multi-threading, it's just a standard interface to extend when encapsulating a block of code in an object.

这篇关于Java线程:如何实现可运行的线程工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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