1、继承Thread类

创建一个新的类,继承自Thread类,然后重写run()方法,在run()方法中编写需要在新线程中执行的任务,最后创建该类的对象,并调用start()方法启动线程。
class MyThread extends Thread {
@Override
public void run() {
// 在这里编写需要在新线程中执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
2、实现Runnable接口
创建一个新的类,实现Runnable接口,然后重写run()方法,在run()方法中编写需要在新线程中执行的任务,最后创建该类的对象,将其作为参数传递给Thread类的构造函数,并调用start()方法启动线程。
class MyRunnable implements Runnable {
@Override
public void run() {
// 在这里编写需要在新线程中执行的任务
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
3、实现Callable接口和FutureTask类
创建一个新的类,实现Callable接口,然后重写call()方法,在call()方法中编写需要在新线程中执行的任务,接着创建一个FutureTask对象,将实现了Callable接口的类的对象作为参数传递给FutureTask的构造函数,最后调用FutureTask对象的get()方法获取任务的返回值。
import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; class MyCallable implements Callable{ @Override public Integer call() throws Exception { // 在这里编写需要在新线程中执行的任务,并返回结果 return null; } } public class Main { public static void main(String[] args) throws InterruptedException, ExecutionException { MyCallable myCallable = new MyCallable(); FutureTask futureTask = new FutureTask<>(myCallable); Thread thread = new Thread(futureTask); thread.start(); Integer result = futureTask.get(); // 等待任务完成并获取结果 } }
4、利用线程池(ExecutorService)和Runnable接口实现懒汉式单例模式(推荐)
使用线程池来管理线程,可以避免手动创建和管理线程带来的繁琐,通过实现Runnable接口并传入一个实现了单例模式的对象,可以实现懒汉式单例模式,线程池会自动分配线程来执行任务。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class MyRunnable implements Runnable {
private static final MyRunnable instance = new MyRunnable(); // 实现懒汉式单例模式的唯一实例对象
private final Object lock = new Object(); // 防止多线程同时访问实例对象时发生冲突的锁对象
private MyRunnable() {} // 将构造方法设为私有,防止外部直接创建实例对象
public static MyRunnable getInstance() { // 实现静态工厂方法,提供获取唯一实例对象的途径
synchronized (lock) { // 当多个线程同时访问时,使用synchronized关键字保证只有一个线程能够进入同步代码块,从而避免多线程同时修改实例对象的问题
if (instance == null) { // 如果实例对象尚未创建,则创建一个新的实例对象并返回给调用者
instance = new MyRunnable();
}
return instance; // 如果实例对象已经创建,则直接返回该实例对象给调用者,无需再次创建新的实例对象浪费资源
}
}
@Override
public void run() { // 在run()方法中编写需要在新线程中执行的任务
}
}