1、继承Thread类
-
首先继承Thread类,然后重写run方法,run方法里面写线程的方法体
-
创建一个主线程,即main方法
-
在main方法中创建线程对象实例,调用start方法开启线程
注意:不要使用run()方法开启线程
public class MyThread extends Thread{
//重写run方法
@Override
public void run() {
System.out.println("继承Thread类创建线程");
}
public static void main(String[] args) {
//创建继承Thread类的对象调用start方法来启动线程
MyThread mythread = new MyThread ();
MyThread .start();
}
}
2、实现Runnable接口
-
首先实现Runnable接口
-
在main方法中创建一个实现该接口的对象并传进Thread类的匿名对象内
-
使用Thread类的匿名对象开启线程
优点:可避免单继承的局限性,方便一个对象被多个线程使用
public class MyThread implements Runnable{
//重写run方法
@Override
public void run() {
System.out.println("实现Runnable接口创建线程");
}
public static void main(String[] args) {
//创建实现Runnable接口的类的对象
MyThread mythread= new MyThread ();
//使用Thread类的匿名对象调用start方法
new Thread(mythread).start();
}
}
3、实现Callable接口
-
实现Callable接口(需要定义返回值类型),重写call方法(需要抛出异常)
-
创建实现Callable接口的对象
-
创建执行服务,提交执行,获取结果
-
关闭服务
import java.util.concurrent.*;
public class MyThread implements Callable {
//重写Callable接口
@Override
public String call() throws Exception {
return "实现Callable接口创建线程";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建实现Callable接口的对象
MyThread mythread = new MyThread ();
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(1);
//提交执行
Future<String> result = service.submit(mythread);
//获取结果
String serviceresult = result.get();
//输出返回结果
System.out.println(serviceresult);
//关闭服务
service.shutdownNow();
}
}
4、创建线程池
-
创建线程池
-
调用execute方法并传入参数(Runnable或Thread接口对象)来启动线程
-
关闭服务
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThread{
public static void main(String[] args) {
//创建线程池
ExecutorService service = Executors.newFixedThreadPool(1);
//调用execute方法启动线程
service.execute(()-> System.out.println("创建线程池启动线程"));
//关闭服务
service.shutdownNow();
}
}