1.多线程定义
多线程(multithreading),是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间执行多于一个线程,进而提升整体处理性能。具有这种能力的系统包括对称多处理机、多核心处理器以及芯片级多处理或同时多线程处理器。在一个程序中,这些独立运行的程序片段叫作“线程”(Thread),利用它编程的概念就叫作“多线程处理”。
多线程比单线程优势在于能够充分利用多核 CPU 的处理能力。
1.1.多线程的实现方式
第一种:继承 Thread 类
public class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println(currentThread().getName() + "线程处理逻辑");
}
public static void main(String[] args) {
new ThreadDemo().start();
new ThreadDemo().start();
new ThreadDemo().start();
new ThreadDemo().start();
new ThreadDemo().start();
}
}
复制代码
第二种:实现 Runnable 接口
public class ThreadDemo2 implements Runnable {
private String name;
public ThreadDemo2(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println(name + "线程处理逻辑");
}
public static void main(String[] args) {
new Thread(new ThreadDemo2("Thread-1")).start();
new Thread(new ThreadDemo2("Thread-2")).start();
new Thread(new ThreadDemo2("Thread-3")).start();
new Thread(new ThreadDemo2("Thread-4")).start();
new Thread(new ThreadDemo2("Thread-5")).start();
}
}
复制代码
2.锁
2.1.synchronized
2.2.lock
3.并发工具类
3.1.并发数据处理工具类
3.2.同步计数器
3.3.异步调用
第一种:线程池
具体示例:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Stream;
public class UserThreadPoolTest {
public static void main(String[] args) throws InterruptedException {
String[] username = new String[100];
for (int i=1; i<=100; i++) {
username[i-1] = "用户" + i;
}
ExecutorService executorService = Executors.newFixedThreadPool(3);
Stream.of(username).forEach(name -> {
System.out.println(name + "开始注册");
executorService.submit(() -> {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + "用户注册后续处理");
});
});
for (int i=1; i<=50; i++) {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("我在干别的" + i);
}
executorService.shutdown();
}
}
复制代码
第二种:CompletableFuture
当有很多请求过来时,我们希望能够立即返回结果,将后续的逻辑进行异步处理,这时可以用 CompletableFuture 来实现。
具体示例:
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
public class UserAsyncTest {
public static void main(String[] args) throws InterruptedException {
String[] username = new String[100];
for (int i=1; i<=100; i++) {
username[i-1] = "用户" + i;
}
Stream.of(username).forEach(name -> {
System.out.println(name + "开始注册");
CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
return name + "注册后续逻辑已经处理完成";
});
completableFuture
.whenComplete((t, u) -> System.out.println(t))
.exceptionally(e -> {
System.out.println(e.getMessage());
return name + "注册异常";
});
});
for (int i=1; i<=30; i++) {
Thread.sleep((long) (Math.random() * 1000));
System.out.println("我在干别的" + i);
}
}
}
复制代码
评论