前言
学习java多线程首先就是要知道如何开启多线程.在java中开启多线程主要有两种方式:
- 继承
Thread
类,然后重写run
方法 - 实现
Runnable
接口,实现run
方法
示例代码
public class App1 {
public static void main(String[] args) {
create1();
create2();
}
/**
* 继承Thread类,重写run方法
*/
public static void create1(){
MyThread thread = new MyThread();
thread.start();
}
static class MyThread extends Thread{
@Override
public void run() {
System.out.println("继承Thread类重写run方法创建线程");
}
}
/**
* 实现Runnable接口,实现run方法
*/
public static void create2(){
Runnable runnable = new MyRunnable();
new Thread(runnable).start();
}
static class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("线程Runnable接口创建线程");
}
}
}
需要注意的是,启动线程是调用start()
方法,而不是run
方法.run
方法只是一个普通的实例方法.
区别
一个是通过继承Thread
来创建,另一个是通过实现Runnable
接口来创建.实际项目开发中,使用Runnable
这种方式比较多.而且使用这种方式我们可以通过线程池来执行我们的任务,同时java中只允许单继承.所以比较推荐实现Runnable
接口这种方式.当然具体使用哪种方式,只要能完成任务都行.
网友评论