一、简介
使用多线程可以提高程序执行的效率,比如我们常见的多线程下载,批量发送文件等功能,常见的实现多线程的方法如下。多线程知识总结见:Java 多线程思维导图。
二、实现多线程的 5 种方法
1、实现 Runnable 接口
public class MyRunnable implements Runnable {
private static AtomicInteger count = new AtomicInteger(0);
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println(Thread.currentThread().getName() + ": " + count.incrementAndGet());
}
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread t1 = new Thread(runnable);
Thread t2 = new Thread(runnable);
Thread t3 = new Thread(runnable);
t1.start();
t2.start();
t3.start();
}
}