创建线程的方法:
首先我们查看Runnable接口的定义:
package java.lang;
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
单纯通过代码,我们可以得到的信息有:
关于Runnable接口更多详细的说明,我想没有什么是比官方文档更精确的了:
/**
* The Runnable
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 run
.
* <p>
* This interface is designed to provide a common protocol for objects that
* wish to execute code while they are active. For example,
* Runnable
is implemented by class Thread
.
* Being active simply means that a thread has been started and has not
* yet been stopped.
* <p>
* In addition, Runnable
provides the means for a class to be
* active while not subclassing Thread
. A class that implements
* Runnable
can run without subclassing Thread
* by instantiating a Thread
instance and passing itself in
* as the target. In most cases, the Runnable
interface should
* be used if you are only planning to override the run()
* method and no other Thread
methods.
* This is important because classes should not be subclassed
* unless the programmer intends on modifying or enhancing the fundamental
* behavior of the class.
*
* @author Arthur van Hoff
* @see java.lang.Thread
* @see java.util.concurrent.Callable
* @since JDK1.0
*/
翻译下:
关于run方法的注释:
/**
* When an object implementing interface Runnable
is used
* to create a thread, starting the thread causes the object's
* run
method to be called in that separately executing
* thread.
* <p>
* The general contract of the method run
is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
翻译下:
当一个实现了Runnable接口的类被用来创建一个线程时,开始这个线程会在这个单独的线程里执行run方法里的代码。run方法设计的理念就是它可以用来干任何事。
看到这里应该说Runnable接口的设计理念和用途已经非常清晰了,简单来说,它就是定义了一个规范,规定任何需要创建线程执行的代码都应该实现runnable接口,并把代码放入到run方法中。当线程启动时,就会在这个线程中执行run方法中的代码。
下面写一个简单的示例来演示Runnable接口的使用:
package org.xtf2009.concurrent.runnable;
public class RunnableDemo implements Runnable {
@Override
public void run() {
System.out.println("I am running in Thread:" + Thread.currentThread().getName());
}
public static void main(String[] args) {
System.out.println("Start main in Thread:"+ Thread.currentThread().getName());
Thread t = new Thread(new RunnableDemo());//创建一个Thread类,传入RunnableDemo的实例
t.start();//线程启动后,就会执行run方法中的代码
System.out.println("End main in Thread:"+ Thread.currentThread().getName());
}
}
看下输出结果:
Start main in Thread:main
End main in Thread:main
I am running in Thread:Thread-0
手机扫一扫
移动阅读更方便
你可能感兴趣的文章