我想大家看 Runnable 的源码会更加容易与容易接受,毕竟它有一个 run 方法 。(如下为其源码)
/** * The <code>Runnable</code> interface should be implemented by any * class whose instances are intended to be executed by a thread. The * class must define a method of no arguments called <code>run</code>. */@FunctionalInterfacepublic interface Runnable { /** * When an object implementing interface <code>Runnable</code> is used * to create a thread, starting the thread causes the object's * <code>run</code> method to be called in that separately executing * thread. */ public abstract void run();}首先,所有打算执行线程的类均可实现这个 Runnable 接口,且必须实现 run 方法 。
它将为各个类提供一个协议,就像 Thread 一样,其实当我们的类实现了 Runnable 的接口后,我们的类与 Thread 是同级,只是可能仅有 run 方法,而没有 Thread 提供的跟丰富的功能方法 。
而对于 run 方法,则是所有实现了 Runnable 接口的类,在调用 start 后,将使其单独执行 run 方法 。
那么我们可以写出这样的测试代码 。
MyThreadRunnable myThreadRunnable = new MyThreadRunnable("Runnabel");myThreadRunnable.run();new Thread(myThreadRunnable).start();Thread thread = new Thread(myThreadRunnable);thread.start();thread.start();//运行效果Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.start(Thread.java:705) at com.github.myself.runner.RunnableApplication.main(RunnableApplication.java:14)这是一个子线程 BY Runnabel这是一个子线程 BY Runnabel这是一个子线程 BY Runnabel同样的,线程是不允许多次启动的,这是不合法的 。
同时,这时我们也看出了使用 Thread 与 Runnable 的区别,当我们要多次启用一个相同的功能时 。
我想 Runnable 更适合你 。
但是,用了这两个方式,我们要如何知道线程的运行结果呢???
FutureTask
这个可能很少人(初学者)用到,不过这个现在是我最感兴趣的 。它很有趣 。
其实还有一个小兄弟,那就是 Callable 。它们是一对搭档 。如果上面的内容,你已经细细品味过,那么你应该已经发现 Callable 了 。
没错,他就在 Runnable 的源码中出现过 。
/** * @author Arthur van Hoff * @see java.lang.Thread * @see java.util.concurrent.Callable * @since JDK1.0 */ @FunctionalInterfacepublic interface Runnable {}那么我们先去看看这个 Callable 吧 。(如下为其源码)
/** * A task that returns a result and may throw an exception. * Implementors define a single method with no arguments called * {@code call}. */@FunctionalInterfacepublic interface Callable<V> { /** * Computes a result, or throws an exception if unable to do so. * * @return computed result * @throws Exception if unable to compute a result */ V call() throws Exception;}其实,这是一个与 Runnable 基本相同的接口,当时它可以返回执行结果与检查异常,其计算结果将由 call() 方法返回 。
那么其实我们现在可以写出一个实现的类 。
public class MyCallable implements Callable { private String name; public MyCallable(String name) { this.name = name; } @Override public Object call() throws Exception { System.out.println("这是一个子线程 BY " + name); return "successs"; }}
推荐阅读
- 地球是迄今为止唯一适合人类生存的星球,研究极端 霍金说人类可以穿越到未来
- Redis的链表结构
- MySQL使用WHERE子句来过滤结果集中的行记录
- 分布式系统中"身份证"是如何生成的?
- 种任性的生活方式 茶器收藏
- Java8之Consumer、Supplier、Predicate和Function攻略
- 细数颜色釉瓷器的美 天然的美
- 若冰类玉的越瓷茶碗
- 五种材质让你了解中国茶具文化
- 建盏和天目的区别 你知道吗
