1.继承Thread类
class MyThread extends Thread {
public void run() {
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000); // 使线程休眠 1 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
2.实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println("Runnable: " + i);
try {
Thread.sleep(1000); // 使线程休眠 1 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
3.实现callable接口
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) {
// 创建 Callable 实例
Callable<Integer> callable = new MyCallable();
// 使用 FutureTask 包装 Callable 实例
FutureTask<Integer> futureTask = new FutureTask<>(callable);
// 创建线程并启动
Thread thread = new Thread(futureTask);
thread.start();
try {
// 获取线程执行结果,这里会阻塞直到线程执行完成并返回结果
int result = futureTask.get();
System.out.println("Result: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 实现 Callable 接口
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i;
}
return sum;
}
}
4.使用匿名内部类
public class Main {
public static void main(String[] args) {
Runnable myRunnable = new Runnable() {
public void run() {
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println("Anonymous Runnable: " + i);
try {
Thread.sleep(1000); // 使线程休眠 1 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
5.使用Lambda表达式
public class Main {
public static void main(String[] args) {
Runnable myRunnable = () -> {
// 线程执行的任务
for (int i = 0; i < 5; i++) {
System.out.println("Lambda Runnable: " + i);
try {
Thread.sleep(1000); // 使线程休眠 1 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}