// 方法一:继承Thread类
class MyThread extends Thread {
public void run() {
System.out.println("线程通过继承Thread类创建并运行");
}
}
// 方法二:实现Runnable接口
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程通过实现Runnable接口创建并运行");
}
}
// 方法三:使用Executor框架(推荐)
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadExample {
public static void main(String[] args) {
// 方法一示例
MyThread thread1 = new MyThread();
thread1.start();
// 方法二示例
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
// 方法三示例
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.submit(() -> {
System.out.println("线程通过Executor框架创建并运行");
});
executorService.shutdown();
}
}
Thread类的子类,并重写其run方法来定义线程的行为。然后通过调用start方法启动线程。Runnable接口并重写run方法,可以将任务传递给一个Thread对象来执行。ExecutorService提供了一种高级的机制来管理和调度线程池中的线程,避免了手动创建和管理线程的复杂性。上一篇:java 有序集合
下一篇:java 并发编程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站