Java 入门学习记录(十)
多线程
普通方法调用和多线程
Process & Thread
- 程序,是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念
- 进程,是执行程序的一次执行过程,是一个动态的概念。是系统资源分配的单位
- 通常在一个进程中可以包含若干的线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是 CPU 调度和执行的单位
很多多线程是模拟出来的,真正的多线程是指有多个 CPU(多核)。如果是模拟出来的多线程,在一个 CPU 的情况下,只能同时执行一条代码,只是因为执行的速度很快,才有同时执行的感觉
线程的创建
创建方式
Thread *
- 自定义线程类继承 Thread 类
- 重写 run() 方法,编写线程执行体
- 创建线程对象,调用 start() 方法执行线程
public class Demo extends Thread{
@Override
public void run() {
// run 多线程体
for (int i = 0; i < 200; i++) {
System.out.println("Thread 多线程 " + i);
}
}
public static void main(String[] args) {
Demo demo = new Demo();
// demo.run(); // 可以理解为仍然是单线程,只是调用了一个方法罢了
demo.start();
for (int i = 0; i < 1000; i++) {
System.out.println("主方法运行:" + i);
}
}
}
注意线程开启不能立即执行,由 CPU 调度执行
多线程小练习
利用多线程下载图片。其中需要使用一个 commons-io 包,可在 传送门 下载后导入项目中使用
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class ThreadDemo1 extends Thread{
private String url;
private String name;
public ThreadDemo1(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("已下载文件: " + name);
}
public static void main(String[] args) {
ThreadDemo1 thread1 = new ThreadDemo1("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java pic001.png");
ThreadDemo1 thread2 = new ThreadDemo1("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java pic002.png");
ThreadDemo1 thread3 = new ThreadDemo1("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java pic003.png");
thread1.start();
thread2.start();
thread3.start();
}
}
class WebDownloader {
public void downloader(String url, String name) {
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("I/O Exception -- downloader");
}
}
}
输出显然不是按照顺序下载的:
Runnable *
- 定义 MyRunnable 类实现 Runnable 接口
- 实现 Run 方法,编写线程执行体
- 创建线程对象,调用 start() 方法启动线程
推荐使用 Runnable,因为 Java 单继承的局限性,方便 一个对象被多个线程使用
多线程操作同一个对象
public class Practice implements Runnable{
private int tickets = 10;
@Override
public void run() {
while (true) {
if (tickets <= 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + tickets-- + "张票");
}
}
public static void main(String[] args) {
Practice practice = new Practice();
new Thread(practice, "小明").start();
new Thread(practice, "小亮").start();
new Thread(practice, "黄牛").start();
}
}
产生了并发问题,在多个线程操作同一个对象的时候,线程不安全,发生了数据紊乱
龟兔赛跑实现 Runnable 接口
public class Race implements Runnable{
private static String winner; // static 保证在调用时只有一个 winner
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// 判断比赛是否结束
System.out.println(Thread.currentThread().getName() + "在跑第 " + i + "步");
boolean flag = gameOver(i);
if (flag) {
break;
}
}
}
// 判断比赛结束函数
private boolean gameOver(int steps) {
if (winner != null) {
return true; // 判断输的另一个线程跳出循环
}{
if (steps >= 100) {
winner = Thread.currentThread().getName();
System.out.println("Winner is " + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race, "Rabbit").start();
new Thread(race, "Turtle").start();
}
}
Winner 的输出是随机的
此时在 run() 方法中添加一个线程休眠,使名为 Rabbit 的线程休眠一段时间,则会发现都是 Turtle 为 Winner
添加如下其中的判断部分
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
// Rabbit 休眠
if (Thread.currentThread().getName() == "Rabbit" && i % 10 == 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 判断比赛是否结束
System.out.println(Thread.currentThread().getName() + "在跑第 " + i + "步");
boolean flag = gameOver(i);
if (flag) {
break;
}
}
}
输出为:
Callable (了解即可)
-
实现 Callable 接口,需要返回值类型
-
重写 call 方法,需要抛出异常
-
创建目标对象
-
创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
-
提交执行:Future result1 = ser.submit(t1);
-
获取结果:boolean r1 = result1.get();
-
关闭服务:ser.shutdownNow();
利用 Callable 改造下载图片
import java.util.concurrent.*;
public class Demo2 implements Callable {
private String url;
private String name;
public Demo2(String url, String name) {
this.url = url;
this.name = name;
}
@Override
public Boolean call() throws Exception{
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("已下载文件: " + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Demo2 thread1 = new Demo2("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java Callpic001.png");
Demo2 thread2 = new Demo2("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java Callpic002.png");
Demo2 thread3 = new Demo2("https://img.php.cn/upload/article/000/000/194/100fff7ac0fffe6c18dbed80db71dd3a.png", "Java Callpic003.png");
// 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
// 提交执行
Future<Boolean> result1 = ser.submit(thread1);
Future<Boolean> result2 = ser.submit(thread2);
Future<Boolean> result3 = ser.submit(thread3);
// 获取结果
boolean r1 = result1.get();
boolean r2 = result2.get();
boolean r3 = result3.get();
// 关闭服务
ser.shutdownNow();
}
}
Callable 的好处就是拥有返回值,并且可以抛出异常
实现静态代理对比 Thread *
public class StaticProxy {
public static void main(String[] args) {
// 代理模式 线程的代理实现了 Runnable 接口,代理的思想!!!
new WeddingCompany(new You()).marry();
new Thread(() -> System.out.println("You Marry!")).start();
}
}
interface Marry {
void marry();
}
// 实际需要结婚的角色 You
class You implements Marry {
@Override
public void marry() {
System.out.println("You marry!");
}
}
// 代理角色,帮助对象结婚
class WeddingCompany implements Marry {
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void marry() {
before();
this.target.marry();
after();
}
private void before() {
System.out.println("布置现场");
}
private void after() {
System.out.println("收取费用");
}
}
真实对象和代理对象都需要实现同一个接口
需要代理一个真实对象
好处:
- 代理对象可以做很多真实对象做不了的事情
- 真实对象专注处理自己的事情
Thread 相当于代理
Lambda 表达式
λ 表达式:
- 避免匿名内部类定义过多
- 其实质属于函数式编程概念
(params) -> expression [ 表达式 ]
(params) -> statement [ 语句 ]
(params) -> { statements }
a -> System.out.println("lamda");
Functional Interface (函数式接口):
- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
public interface Runnable() {
public abstract void run();
}
- 对于函数式接口,我们可以通过 lambda 表达式来创建该接口的对象
public class Demo3 {
public static void main(String[] args) {
hello hello = new hello();
hello.test(2);
// 匿名内部类
Lambda lambda = new Lambda() {
@Override
public void test(int a) {
System.out.println("匿名内部类" + a);
}
};
// lambda
lambda = (int a) -> {
System.out.println("lambda!!!"+ a);
};
// lambda 的简化1: 参数类型
lambda = (a) -> {
System.out.println("lambda!!!"+ a);
};
// lambda 的简化2: 括号
lambda = a -> {
System.out.println("lambda!!!"+ a);
};
// lambda 的简化3: 单行可去掉大括号
lambda = a -> System.out.println("lambda!!!"+ a);
}
}
interface Lambda{
void test(int a);
}
class hello implements Lambda{
@Override
public void test(int a) {
System.out.println("hello.test()" + a);
}
}
lambda 必须是函数式接口,即只有一个方法的接口
内容只有一行时可以简化大括号;参数只有一个可以简化掉小括号
线程状态
创建状态 - 就绪状态 - 阻塞状态 – 运行状态 – 死亡状态
方法 | 说明 |
---|---|
setPriority(int newPriority) | 更改线程优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程体休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程 (不推荐使用) |
boolean isAlive() | 测试线程是否处于活动状态 |
线程停止
中断线程:不推荐使用 JDK 提供的 stop()、destroy() 方法。
推荐使用:创建标志位作为终止变量,从而终止线程的运行
public class Demo4 implements Runnable{
// 设置标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println("Run Thread1..." + i++);
}
}
// 设置一个公开的 stop() 来停止线程,转换标志位
void stop() {
this.flag = false;
}
public static void main(String[] args) {
Demo4 demo4 = new Demo4();
new Thread(demo4).start();
for (int i = 0; i < 100; i++) {
demo4.stop();
System.out.println("Finished!!!");
}
}
}
线程休眠
- sleep(time) 指定当前线程阻塞的毫秒数
- sleep 存在异常 InterruptedException
- sleep 时间达到后进入就绪状态
- sleep 可以模拟网络延时,倒计时等
- 每一个对象都有一个锁,sleep 不会释放锁
import java.text.SimpleDateFormat;
import java.util.Date;
import static java.lang.System.currentTimeMillis;
public class Demo5 {
public static void main(String[] args) throws Exception {
countdown(10);
}
public static void countdown(int count) throws Exception{
int i = count;
while (!(i < 0)) {
Thread.sleep(1000);
System.out.println(i-- + " AND " + new SimpleDateFormat("HH:mm:ss").format(new Date(currentTimeMillis())));
}
}
}
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 礼让就是让 CPU 重新调度,所以礼让不一定成功
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield, "A").start();
new Thread(myYield,"B").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 线程开始");
Thread.yield();
System.out.println(Thread.currentThread().getName() + " 线程结束");
}
}
礼让就是在当前执行阶段给其他线程一个机会
线程加入
Join 合并线程,待此线程执行完成后,再执行其他线程。此时其他线程阻塞
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 500; i++) {
System.out.println("SubThread " + i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 1000; i++) {
if (i == 200) {
thread.join();
}
System.out.println("mainThread " + i);
}
}
}
代码为在主线程运行到 200 之前相互争夺 CPU 调度,当主线程到 200 后,子线程 join,全部运行完后再执行主线程
监测线程状态
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("--------------");
});
// 观察状态
Thread.State state = thread.getState(); // Enum 的状态
System.out.println(state); // NEW
// Start
thread.start();
System.out.println(thread.getState()); // 启动后状态
while (state != Thread.State.TERMINATED) {
Thread.sleep(200);
state = thread.getState();
System.out.println(state);
}
}
}
线程优先级
-
Java 提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
-
线程的优先级用数字表示,范围从 1~10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
-
使用下面方式改变或获取优先级
- getPriority()
- setPriority(int xxx)
public class TestPriority {
public static void main(String[] args) {
// 主线程优先级
System.out.println(Thread.currentThread().getName() + " Priority " + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
Thread thread6 = new Thread(myPriority);
// setPriority
thread1.start();
thread2.setPriority(4);
thread2.start();
thread3.setPriority(1);
thread3.start();
thread4.setPriority(2);
thread4.start();
thread5.setPriority(9);
thread5.start();
thread6.setPriority(7);
thread6.start();
}
}
class MyPriority implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " Priority " + Thread.currentThread().getPriority());
}
}
这里的优先级只是意味着能够获取更高的调度概率,并不是真的优先级高的就先运行,运行了许多次我的都是随机的,竟然没有一次 9 优先级的第一次运行 ······
守护线程
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕
虚拟机不用等待守护线程执行完毕
public class TestDaemon {
public static void main(String[] args) {
DaemonGod daemonGod = new DaemonGod();
myDaemon myDaemon = new myDaemon();
Thread thread = new Thread(daemonGod);
thread.setDaemon(true);
thread.start();
new Thread(myDaemon).start();
}
}
class DaemonGod implements Runnable {
@Override
public void run() {
while (true) {
System.out.println("I am Daemon you!!");
}
}
}
class myDaemon implements Runnable {
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("Daemoned --- People");
}
System.out.println("------Bye World!!!------");
}
}
线程同步 *
并发: 一个对象同时被多个线程(交替?)操作
处理多线程问题时,多个线程访问同一个对象,并且某些线程还要修改这个对象,这时候需要线程同步。线程同步其实是一种等待机制,多个需要访问一个对象的线程进入这个对象的等待池形成队列
形成条件:队列 + 锁(保证安全性)
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制 synchronized,当一个线程获得对象的排他锁,独占资源,其他线程必须等待,使用后释放锁即可。存在以下问题
- 一个线程持有锁会导致其他所有需要此锁的线程挂起
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换 和 调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程释放锁,会导致优先级倒置,引起性能问题
三大不安全案例
抢票案例
public class Demo6 {
public static void main(String[] args) {
buyTickets buyTickets = new buyTickets();
new Thread(buyTickets, "Amy").start();
new Thread(buyTickets, "David").start();
}
}
class buyTickets implements Runnable {
private int tickets = 10;
private boolean flag = true;
@Override
public void run() {
while (flag) {
buy(); // synchronized 其他线程不能进入从而干扰变量的值
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() { // 加 synchronized 上锁
if (tickets <= 0) {
flag = false;
return;
}
System.out.println(Thread.currentThread().getName() + " 拿到了第 " + tickets-- + " 张票");
}
}
输出中会发现有同一张票被多人抢去的情况
取钱案例
public class UnSafeBank {
public static void main(String[] args) {
Account account = new Account(1000000, "Account");
Drawing me = new Drawing(account, 1000000, "me");
Drawing friend = new Drawing(account, 600000, "friend");
me.start();
friend.start();
}
}
class Account {
int money;
String name;
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread {
Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
if (account.money - drawingMoney < 0) {
System.out.println("余额不足!!!");
return; // 停止方法继续运行
}
// sleep 放大问题的发生性,让另一个线程在计算之前进入判断
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney; // 账户对象的金额
nowMoney = nowMoney + drawingMoney; // 取钱用户的金额
System.out.println(account.name + " 的余额为 " + account.money);
System.out.println(this.getName() + " 身上拥有金额 " + nowMoney); // Thread.currentThread().getName() == this.getName()
}
}
这里面两个线程操作同一对象和变量,sleep 放大问题发生性
添加 List
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> list.add(Thread.currentThread().getName())).start();
}
Thread.sleep(2000);
System.out.println(list.size());
}
}
这个输出中会发现有很多时候 list 的 size 不会到 10000,小于 10000,线程运行时将名称放到了 list 的同一位置
-
由于我们可以通过 private 关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法:
synchronized 方法 和 synchronized 块
同步方法 public synchronized void method(int args) {}
-
synchronized 方法控制对 ”对象“ 的访问,每个对象对应一把锁,每个 synchronized 方法都必须获得调用该方法的对象的锁才能执行。否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
一个线程访问一个对象中的synchronized(this)同步代码块时,其他试图访问该对象的线程将被阻塞。
缺陷:若将一个大的方法申明为 synchronized 将会影响效率
同步块
synchronized (Obj // 临界资源对象) {
code
}
如在上面的 list 代码中添加同步代码块
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(() -> {
synchronized(list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(2000); // 主线程休眠,使子线程能够运行完
System.out.println(list.size());
}
}
CopyOnWriteArrayList
import java.util.concurrent.CopyOnWriteArrayList;
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 1000; i++) {
new Thread(() -> list.add(Thread.currentThread().getName())).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
没有使用 synchronized 代码块,因为这个 ArrayList 是安全线程的,源码不同
死锁
多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或多个线程都在等待对方释放资源,从而都停止执行的情形。某一个同步块同时拥有两个以上对象的锁时,就可能发生死锁问题
public class DeadLock {
public static void main(String[] args) {
MakeUp a = new MakeUp(1, "A");
MakeUp b = new MakeUp(0, "B");
a.start();
b.start();
}
}
class LipStick {
}
class Mirror {
}
class MakeUp extends Thread {
static LipStick lipStick = new LipStick();
static Mirror mirror = new Mirror();
int choice;
String name;
public MakeUp(int choice, String name) {
this.choice = choice;
this.name = name;
}
@Override
public void run() {
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void makeup() throws InterruptedException {
if (choice == 1) {
synchronized (lipStick) {
System.out.println(this.name + "口红锁");
Thread.sleep(1000);
}
synchronized (mirror) {
System.out.println(this.name + "镜子锁");
}
} else {
synchronized (mirror) {
System.out.println(this.name + "镜子锁");
Thread.sleep(2000);
}
synchronized (lipStick) {
System.out.println(this.name + "口红锁");
}
}
}
}
会发现输出的时候先有两个输出,需要等待 1s 才能继续输出,因为 sleep 不会释放锁,程序互斥锁,死锁
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对以获得额定资源保持不放
- 不剥夺条件:进程以获得额定资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
Lock(锁)
从 JDK 5.0 开始,java 提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用 Lock 对象充当
java.util.concurrent.locks.Lock 接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源独占访问,每次只能有一个线程对 Lock 对象加锁,线程开始访问共享资源之前应先获得 Lock 对象
ReentrantLock 类实现了 Lock,它拥有与 synchronized 相同的并发性和内存语义。在实现线程安全的控制中,比较常用的是 ReentrantLock,可以显式加锁、释放锁
class Demo{
private final ReentrantLock lock = new ReentrantLock();
public void method() {
lock.lock();
try{
// 保证线程安全的代码
}finall {
lock.unlock();
// 如果同步代码有异常,将 unlock() 写入 finally 块中
}
}
}
Lock 是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized 是隐式锁,出了作用域自动释放
Lock 只有代码块锁,synchronized 有代码块锁和方法锁
使用 Lock,JVM 将花费较少的时间来调度线程性能更好。并且具有更好的扩展性(提供更多子类)
优先使用顺序:
Lock -> 同步代码块(已经进入了方法体,分配了相应资源)-> 同步方法(在方法之外)
线程协作
线程通信(生产者消费者关系)
Java 提供了几个方法解决线程之间的通信问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待,直到其他线程通知,与 sleep 不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用 wait() 方法的线程,优先级别高的线程优先调度 |
均是 Object 类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常 IlegalMonitorStateException
解决方式 1
并发协作模型 “生产者/消费者模式” -> 管程法
- 生产者:负责生产数据的模块(可能是方法,对象,线程,进程)
- 消费者:负责处理数据的模块(可能是方法,对象,线程,进程)
- 缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区"
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
解决方式 2
并发协作模型 “生产者/消费者模式” -> 信号灯法
使用一个 boolean flag 来控制是否操作,相当于缓冲区只有 1 的管程法
线程池
背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
好处:
-
提高响应速度(减少了创建新线程的时间)
-
降低资源消耗(重复利用线程池中线程,不需要每次都创建)
-
便于线程管理
- corePoolSize:核心池的大小
- maximumPoolSize:最大线程数
- keepAliveTime:线程没有任务时最多保持多长时间后会终止
包括之前的 Callable 接口,还有以下对 Runnable 接口的使用
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
// 创建服务和线程池
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new myThread());
service.execute(new myThread());
service.execute(new myThread());
service.execute(new myThread());
// 关闭
service.shutdown();
}
}
class myThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " num "+ i);
}
}
}