创建线程的三种方式的对比
1. 采用实现 Runnable、Callable 接口的方式创建多线程时,线程类只是实现了 Runnable 接口或 Callable 接口,还可以继承其他类。 2. 使用继承 Thread 类的方式创建多线程时,编写简单,如果需要访问当前线程,则无需使用 Thread.currentThread() 方法,直接使用 this 即可获得当前线程。 3.Thread 、Runnable方式都可以用来创建线程去执行子任务,但Java只允许单继承,如果自定义类需要继承其他类则只能选择实现Runnable接口。
首先,为了实现 Runnable要方法调用 run():
public void run(){
}
其次,在类中实例化一个线程对象:
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
新线程创建之后,调用线程对象的 start() 方法运行。
void start()
代码如下:
class MyRunnable implements Runnable{
public MyRunnable() {
}
public void run() {
}
}
public class Test {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}