文章目录
应用场景
并发编程的目的是通过同时执行多个任务来提高程序的性能、响应能力和资源利用率。
创建多线程的方式
1、继承Thread类
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " run()方法正在执行...");
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
System.out.println(Thread.currentThread().getName() + " main() 方法执行结束");
}
}
2、实现Runnable接口
public class MyRunnable implements Runnable {
public void run() {
System.out.println(Thread.currentThread().getName() + " run()方法执行中... ");
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
System.out.println(Thread.currentThread().getName() + " main() 方法执行完成");
}
}
3、实现Callable接口
public class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
System.out.println(Thread.currentThread().getName() + " call() 方法执行中...");
return 1;
}
public static void main(String[] args) {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
try{
Thread.sleep(1000);
System.out.println("返回结果 " + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " main() 方法执行完成");
}
}
4、使用线程池
4.1 单线程池 (Executors.newSingleThreadExecutor)
适用于需要保证任务按顺序执行的场景。
public class SingleThreadExecutorTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 5; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " run()方法执行中... ");
}
});
}
System.out.println("线程任务开始执行....");
executorService.shutdown();
}
}
4.2 固定大小的线程池 (Executors.newFixedThreadPool)
适用于负载较为恒定的场景。
public class FixedThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
});
}
executorService.shutdown();
}
}
4.3 缓存的线程池 (Executors.newCachedThreadPool)
适用于执行大量短期异步任务的场景,可以自动回收空闲线程。
public class CachedThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
});
}
executorService.shutdown();
}
}
4.4 调度线程池 (newScheduledThreadPool)
创建一个可以延迟或定期执行任务的线程池。
public class ScheduledThreadPoolExample {
public static void main(String[] args) {
// 创建一个具有5个线程的调度线程池
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
// 安排一个定期执行的任务
//1:表示初始延迟时间,即任务第一次执行前的等待时间为1秒。
//3:表示后续执行的间隔时间,即任务第一次执行后,每隔3秒执行一次。
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Scheduled task is running: " + Thread.currentThread().getName());
}
}, 1, 3, TimeUnit.SECONDS);
}
}
4.5 自定义ThreadPoolExecutor
public class CustomThreadPoolExecutorExample {
public static void main(String[] args) {
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2,
4,
60,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()
);
for (int i = 0; i < 10; i++) {
executor.execute(new Runnable() {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
});
}
executor.shutdown();
}
}