在Java中,多线程的实现方式分别为:继承Thread类、实现Runnable接口以及使用Callable和Future实现多线程,前两种都没有返回值,而通过用Callable和Future实现的多线程有返回值,我们来分别介绍一下这三种实现多线程的方式:
第一种:继承Thread类
①定义一个类、继承Thread类;
②在这个类里面重写run()方法;
③创建这个类的对象;
④启动线程。
代码演示:
/创建MyThread继承Thread类
public class MyThread extends Thread{
//重写run方法
@Override
public void run() {
System.out.println("线程启动了");
}
}
public class Test {
public static void main(String[] args) {
//创建MyThread对象
MyThread mt = new MyThread();
//启动线程
mt.start();
}
}
第二种:实现Runnable接口
①定义一个类MyRunnable实现Runnable接口;
②在MyRunnable类中重写run()方法;
③创建MyRunnable类的对象;
④创建Thread类对象,把MyRunnable对象作为参数传递给该对象;