Java多线程是指在一个Java程序中同时执行多个线程,它可以提高程序的并发性和响应能力。Java中实现多线程的方式:
继承Thread类
实现Runnable接口
Executor框架
Callable
Future
线程池
1 继承Thread类
public class ThreadDemo {
public static void main(String[] args) {
// 创建10个线程并启动
for (int i = 0; i < 10; i++) {
MyThread thread = new MyThread(i);
thread.start();
}
}
}
class MyThread extends Thread {
private int id;
public MyThread(int id) {
this.id = id;
}
public void run() {
System.out.println("Thread " + id + " is running");
try {
Thread.sleep(1000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}