java中实现多线程有几种方式,请举例
时间: 2023-12-14 20:04:14 浏览: 93
Java中实现多线程的方式有以下几种:
1. 继承Thread类,重写run()方法。例如:
```
class MyThread extends Thread {
public void run() {
// 线程执行代码
}
}
MyThread thread = new MyThread();
thread.start();
```
2. 实现Runnable接口,重写run()方法。例如:
```
class MyRunnable implements Runnable {
public void run() {
// 线程执行代码
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
```
3. 实现Callable接口,重写call()方法。例如:
```
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 线程执行代码
return result;
}
}
MyCallable callable = new MyCallable();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(callable);
```
4. 使用线程池。例如:
```
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 100; i++) {
Runnable task = new MyRunnable();
executor.submit(task);
}
executor.shutdown();
```
阅读全文