2020-11-17

多线程
学前总结
进程与线程的区别
在这里插入图片描述

多线程的方法执行顺序
在这里插入图片描述

多线程核心知识点
在这里插入图片描述

实现多线程
创建线程有3种方法,分别是继承Thread类,实现Runnable接口和实现Callable接口。
在这里插入图片描述

继承Thread类
在这里插入图片描述

// 继承父类实现多线程
public class TestThread extends Thread {

@Override
public void run() {
    for (int i = 0; i < 300; i++) {
        System.out.println("我是分支线程,打印" + i);
    }
}

public static void main(String[] args) {
    TestThread testThread = new TestThread();
    testThread.start();
    for (int i = 0; i < 2000; i++) {
        System.out.println("我是主线程,打印" + i);
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
执行结果


通过继承Thread类,我是主线程,打印547
通过继承Thread类,我是主线程,打印548
通过继承Thread类,我是主线程,打印549
通过继承Thread类,我是分支线程,打印195
通过继承Thread类,我是分支线程,打印196
通过继承Thread类,我是分支线程,打印197
通过继承Thread类,我是分支线程,打印198
通过继承Thread类,我是分支线程,打印199
通过继承Thread类,我是主线程,打印550
通过继承Thread类,我是主线程,打印551
通过继承Thread类,我是分支线程,打印200
通过继承Thread类,我是分支线程,打印201

1
2
3
4
5
6
7
8
9
10
11
12
13
14
主线程和分支线程会同步进行,服从CPU调度,先后顺序不确定。

实现Runnable接口
在这里插入图片描述

// 实现Runnable接口实现多线程
public class TestRunnable implements Runnable{

@Override
public void run() {
    for (int i = 0; i < 300; i++) {
        System.out.println("我是分支线程,打印" + i);
    }
}

public static void main(String[] args) {
    TestRunnable testRunnable = new TestRunnable();
    // 通过线程对象来开启线程,代理
    new Thread(testRunnable).start();
    for (int i = 0; i < 2000; i++) {
        System.out.println("我是主线程,打印" + i);
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
执行结果


通过实现Runnable接口,我是分支线程,打印252
通过实现Runnable接口,我是分支线程,打印253
通过实现Runnable接口,我是主线程,打印383
通过实现Runnable接口,我是主线程,打印384
通过实现Runnable接口,我是主线程,打印385
通过实现Runnable接口,我是主线程,打印386
通过实现Runnable接口,我是主线程,打印387
通过实现Runnable接口,我是主线程,打印388
通过实现Runnable接口,我是主线程,打印389
通过实现Runnable接口,我是分支线程,打印254
通过实现Runnable接口,我是分支线程,打印255

1
2
3
4
5
6
7
8
9
10
11
12
13
继承Thread类和实现Runnable接口的对比
继承Thread类
子类继承Thread类具备多线程能力
启动线程:子类对象.start()
不推荐使用:避免OOP单继承局限性
实现Runnable接口
实现接口Runnable具有多线程能力
启动线程:传入目标对象+Thread对象.start()
推荐使用:避免单继承的局限性,灵活方便,方便同一个对象被多个线程使用
龟兔赛跑案例
在这里插入图片描述

// 模拟龟兔赛跑
public class Race implements Runnable {

// 胜利者
private static String winner;

@Override
public void run() {
    for (int i = 1; i <= 100; i++) {
        // 如果是兔子,try语句块的i++表示一次跑两步比乌龟快,但是当兔子快要到终点时,睡觉1秒
        if (Thread.currentThread().getName().equals("兔子") && i > 90) {
            try {
                i++;
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 判断比赛是否结束
        boolean flag = gameOver(i);
        if (flag)
            break;
        System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "步");
    }
}

// 判断是否完成比赛
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, "兔子").start();
    new Thread(race, "乌龟").start();
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
执行结果


兔子–>跑了88步
兔子–>跑了89步
兔子–>跑了90步
乌龟–>跑了79步
乌龟–>跑了80步
乌龟–>跑了81步
乌龟–>跑了82步
乌龟–>跑了83步
乌龟–>跑了84步

乌龟–>跑了96步
乌龟–>跑了97步
乌龟–>跑了98步
乌龟–>跑了99步
winner is 乌龟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
实现Callable接口
使用ExecutorService创建执行服务
在这里插入图片描述
// 实现callable接口实现多线程
/**

  • 1.可以定义返回值

  • 2.可以抛出异常
    */
    public class TestCallable implements Callable {

    @Override
    public Boolean call() throws Exception {
    return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
    TestCallable testCallable1 = new TestCallable();
    TestCallable testCallable2 = new TestCallable();
    TestCallable testCallable3 = new TestCallable();

     // 创建执行服务
     ExecutorService service = Executors.newFixedThreadPool(3);
     // 提交执行
     Future<Boolean> r1 = service.submit(testCallable1);
     Future<Boolean> r2 = service.submit(testCallable2);
     Future<Boolean> r3 = service.submit(testCallable3);
     // 获取结果
     String result1 = "结果1:" + r1.get();
     String result2 = "结果2:" + r2.get();
     String result3 = "结果3:" + r3.get();
     System.out.println(result1);
     System.out.println(result2);
     System.out.println(result3);
     // 关闭服务
     service.shutdown();
    

    }
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    执行结果

结果1:true
结果2:true
结果3:true
1
2
3
使用FutureTask对象
创建Callable子类的实例化对象
创建FutureTask对象,并将Callable对象传入FutureTask的构造方法中 (FutureTask实现了Runnable接口和Future接口)
实例化Thread对象,并在构造方法中传入FurureTask对象
启动线程
// 实现callable接口实现多线程
public class TestCallable2 implements Callable {

@Override
public String call() throws Exception {
    return "hello world!";
}

public static void main(String[] args) throws ExecutionException, InterruptedException {
    FutureTask<String> ft = new FutureTask<>(new TestCallable2());
    new Thread(ft).start();
    String result = ft.get();
    System.out.println(result);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
执行结果

hello world!
1
线程状态
在这里插入图片描述
注:线程start()启动之后并不是直接到运行状态,而是先到就绪状态等待CPU调度,获得CPU资源才会变成运行状态。阻塞状态解除是同理,也会先变成就绪状态。

获得线程状态
// 观察测试线程的状态,线程中断或者结束之后不能再次开始
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();

    // NEW
    System.out.println(state);
    // 观察启动后
    thread.start();
    state = thread.getState();
    System.out.println(state);

    // 只要线程不终止,就一起输出状态
    while (state != Thread.State.TERMINATED) {
        Thread.sleep(100);
        // 更新线程状态
        state = thread.getState();
        // 输出状态
        System.out.println(state);
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
执行结果

NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING

TIMED_WAITING
TIMED_WAITING

TERMINATED
1
2
3
4
5
6
7
8
9
线程基本方法
在这里插入图片描述

1.线程停止-stop
在这里插入图片描述

// 不推荐使用JDK提供的stop()和destroy()方法
// 推荐线程自己停止下来
public class TestStop implements Runnable {

private boolean flag = true;

@Override
public void run() {
    int i = 0;
    while (flag) {
        System.out.println("run...thread..." + i++);
    }
}

public void stop() {
    this.flag = false;
}

public static void main(String[] args) throws InterruptedException {
    TestStop testStop = new TestStop();
    new Thread(testStop).start();

    for (int i = 0; i < 4000; i++) {
        System.out.println("main---" + i);
        if (i == 3900) {
            testStop.stop();
            System.out.println("线程该停止了");
        }
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
执行结果


run…thread…1992
main—3634
main—3635
main—3636
run…thread…1993
run…thread…1994
main—3637
main—3638

main—3900
线程该停止了
main—3901
1
2
3
4
5
6
7
8
9
10
11
12
13
2.线程休眠-sleep
在这里插入图片描述

// 每隔一秒打印当前时间
public class TestSleep2 {

public static void main(String[] args) {
    // 打印当前系统时间
    Date startTime = new Date(System.currentTimeMillis()); //获取当前系统时间
    while (true) {
        try {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());// 更新当前时间
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// 模拟倒计时
public static void tenDown() throws InterruptedException {
    int num = 10;
    while (true) {
        Thread.sleep(1000);
        System.out.println(num--);
        if (num <= 0)
            break;
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
执行结果

11:10:59
11:11:00
11:11:01
11:11:02

1
2
3
4
5
3.线程礼让-yield
在这里插入图片描述

// 测试礼让线程
// 礼让不一定成功,看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() + "线程停止执行");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
测试结果-礼让成功

a线程开始执行
b线程开始执行
a线程停止执行
b线程停止执行
1
2
3
4
测试结果-礼让失败

a线程开始执行
a线程停止执行
b线程开始执行
b线程停止执行
1
2
3
4
4.线程强制执行-join
在这里插入图片描述

// 测试join方法
// 想象为插队
public class TestJoin implements Runnable {

@Override
public void run() {
    for (int i = 0; i < 500; i++) {
        System.out.println("线程vip来了....");
    }
}

public static void main(String[] args) throws InterruptedException {
    // 启动我们的线程
    TestJoin testJoin = new TestJoin();
    Thread thread = new Thread(testJoin);
    thread.start();

    for (int i = 0; i < 500; i++) {
        if (i == 200)
            thread.join();
        System.out.println("main..." + i);
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
执行结果


main…198
main…199
线程vip来了…
线程vip来了…

线程vip来了…
线程vip来了…
main…200
1
2
3
4
5
6
7
8
9
注:在插队过程中不会释放CPU资源,直至该线程结束

5.线程优先级-priority
在这里插入图片描述

// 测试线程的优先级
// 优先级:1-10,默认都是5
public class TestPriority {

public static void main(String[] args) {
    // 主线程默认优先级
    System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

    MyPriority myPriority = new MyPriority();

    Thread t1 = new Thread(myPriority);
    Thread t2 = new Thread(myPriority);
    Thread t3 = new Thread(myPriority);
    Thread t4 = new Thread(myPriority);
    Thread t5 = new Thread(myPriority);
    Thread t6 = new Thread(myPriority);

    // 先设置优先级
    t1.start();

    // 一定要先设置优先级,再启动线程
    t2.setPriority(1);
    t2.start();

    t3.setPriority(4);
    t3.start();

    t4.setPriority(Thread.MAX_PRIORITY);
    t4.start();

    t5.setPriority(7);
    t5.start();

    t6.setPriority(8);
    t6.start();
}

}

class MyPriority implements Runnable {

@Override
public void run() {
    System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
执行结果

main–>5
Thread-3–>10
Thread-4–>7
Thread-5–>8
Thread-0–>5
Thread-2–>4
Thread-1–>1
1
2
3
4
5
6
7
注:设置的优先级只有权重更大,可以理解为概率更大,但并不一定是严格按照优先级执行。比如我运行了39次出了这个结果~~~

main–>5
Thread-3–>10
Thread-4–>7
Thread-5–>8
Thread-0–>5
Thread-2–>4
Thread-1–>1
1
2
3
4
5
6
7
守护线程
在这里插入图片描述

/**

  • 线程分为用户线程和守护线程,默认都是用户线程

  • 虚拟机必须确保用户线程执行完毕

  • 虚拟机不用等待守护线程执行完毕

  • 如:后台记录操作日志,监控内存,垃圾回收等待…
    */
    public class TestDaemon {

    public static void main(String[] args) {
    God god = new God();
    You you = new You();

     Thread thread = new Thread(god);
     thread.setDaemon(true); // 默认是false表示是用户线程,正常的线程都是用户线程....
    
     thread.start();// 上帝守护线程启动
    
     new Thread(you).start();
    

    }
    }

// 上帝
class God implements Runnable {

@Override
public void run() {
    while (true) {
        System.out.println("上帝保佑着你");
    }
}

}

// 你
class You implements Runnable {

@Override
public void run() {
    for (int i = 0; i < 36500; i++) {
        System.out.println("你一生都在开心的活着");
    }
    System.out.println("---------goodbye! world!------------");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
执行结果


上帝保佑着你
上帝保佑着你
上帝保佑着你
你一生都在开心的活着
你一生都在开心的活着
上帝保佑着你
上帝保佑着你
上帝保佑着你
你一生都在开心的活着
你一生都在开心的活着
---------goodbye! world!------------
1
2
3
4
5
6
7
8
9
10
11
12
注:setDaemon(true) 可以将该线程设置为守护线程,虚拟机不用等待守护线程执行完毕。

线程不安全案例
买票案例
// 不安全的买票
// 线程不安全,有负数
public class UnsafeBuyTicket {

public static void main(String[] args) {
    BuyTicket station = new BuyTicket();
    new Thread(station, "苦逼的我").start();
    new Thread(station, "厉害的你们").start();
    new Thread(station, "可恶的黄牛").start();
}

}

class BuyTicket implements Runnable {

// 票
private int ticketNum = 10;
// 外部停止方式
private boolean flag = true;

@Override
public void run() {
    // 买票
    while (flag) {
        try {
            buy();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void buy() throws InterruptedException {
    // 判断是否有票
    if (ticketNum <= 0) {
        flag = false;
        return;
    }
    // 模拟延时
    Thread.sleep(100);
    System.out.println(Thread.currentThread().getName() + "-->拿到第" + ticketNum-- + "张票");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
执行结果

厉害的你们–>拿到第9张票
苦逼的我–>拿到第10张票
可恶的黄牛–>拿到第8张票
可恶的黄牛–>拿到第7张票
厉害的你们–>拿到第6张票
苦逼的我–>拿到第7张票
可恶的黄牛–>拿到第5张票
厉害的你们–>拿到第5张票
苦逼的我–>拿到第4张票
苦逼的我–>拿到第3张票
可恶的黄牛–>拿到第2张票
厉害的你们–>拿到第3张票
可恶的黄牛–>拿到第0张票
苦逼的我–>拿到第-1张票
厉害的你们–>拿到第1张票
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
可以看到票数出现了-1,并且同一张票被多个人拿到。

买票案例-解决方法-方法加锁
在买票方法上加同步锁 synchronized ,即同一时间只有一个对象调用该方法。

public class UnsafeBuyTicket {

public static void main(String[] args) {
    BuyTicket station = new BuyTicket();
    new Thread(station, "苦逼的我").start();
    new Thread(station, "厉害的你们").start();
    new Thread(station, "可恶的黄牛").start();
}

}

class BuyTicket implements Runnable {

// 票
private int ticketNum = 10;
// 外部停止方式
private boolean flag = true;

@Override
public void run() {
    // 买票
    while (flag) {
        try {
            buy();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

// synchronized 同步方法
public synchronized void buy() throws InterruptedException {
    // 判断是否有票
    if (ticketNum <= 0) {
        flag = false;
        return;
    }
    // 模拟延时
    Thread.sleep(100);
    System.out.println(Thread.currentThread().getName() + "-->拿到第" + ticketNum-- + "张票");
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
执行结果

厉害的你们–>拿到第10张票
厉害的你们–>拿到第9张票
可恶的黄牛–>拿到第8张票
苦逼的我–>拿到第7张票
苦逼的我–>拿到第6张票
苦逼的我–>拿到第5张票
可恶的黄牛–>拿到第4张票
可恶的黄牛–>拿到第3张票
可恶的黄牛–>拿到第2张票
可恶的黄牛–>拿到第1张票
1
2
3
4
5
6
7
8
9
10
既然加锁可以保证安全,为什么不都加锁呢,在带来安全的同时肯定也要做出牺牲。

在这里插入图片描述

银行取钱案例
public class UnsafeBank {

public static void main(String[] args) {
    Account account = new Account(100, "建设银行");

    Drawing you = new Drawing(account, 50, "你");
    Drawing wife = new Drawing(account, 100, "wife");
    you.start();
    wife.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(Thread.currentThread().getName() + "要取钱,钱不够取不了");
        return;
    }
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println(this.getName() + "要取" + drawingMoney + "元钱,此时余额为" + account.money);
    // 卡内余额 = 余额 - 你取的钱
    account.money = account.money - drawingMoney;
    // 你手里的钱
    nowMoney = nowMoney + drawingMoney;
    System.out.println(this.getName() + "取钱结束,此时" + account.name + "余额为:" + account.money);
    System.out.println(this.getName() + "手里的钱:" + nowMoney);
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
执行结果

你要取50元钱,此时余额为100
wife要取100元钱,此时余额为100
你取钱结束,此时建设银行余额为:50
wife取钱结束,此时建设银行余额为:-50
你手里的钱:50
wife手里的钱:100
1
2
3
4
5
6
只有100元的帐户发现取出了150元,帐户余额为-50,这显然是不合常理的。

银行取钱案例-解决方法-代码块加锁
synchronized (account) 被锁对象称之为同步监视器,它可以是任何对象。

第一个线程访问,锁定同步监视器,执行其中代码。
第二个线程访问,发现同步监视器被锁定,无法访问。
第一个线程访问完毕,解锁同步监视器。
第二个线程访问,发现同步监视器没有锁,然后锁定并访问。
public class UnsafeBank {

public static void main(String[] args) {
    Account account = new Account(100, "建设银行");

    Drawing you = new Drawing(account, 50, "你");
    Drawing wife = new Drawing(account, 100, "wife");
    you.start();
    wife.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() {
    synchronized (account) {
        // 判断有没有钱
        if (account.money - drawingMoney < 0) {
            System.out.println(Thread.currentThread().getName() + "要取钱,钱不够取不了");
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(this.getName() + "要取" + drawingMoney + "元钱,此时余额为" + account.money);
        // 卡内余额 = 余额 - 你取的钱
        account.money = account.money - drawingMoney;
        // 你手里的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(this.getName() + "取钱结束,此时" + account.name + "余额为:" + account.money);
        System.out.println(this.getName() + "手里的钱:" + nowMoney);
    }
}

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
执行结果

你要取50元钱,此时余额为100
你取钱结束,此时建设银行余额为:50
你手里的钱:50
wife要取钱,钱不够取不了
1
2
3
4
死锁
死锁的定义
在这里插入图片描述

形成死锁的必要条件
在这里插入图片描述
注:以上四个条件只要破坏其中做任意一个或多个,即可避免死锁发生。

死锁案例
// 死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class TestDeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0, “灰姑娘”);
Makeup g2 = new Makeup(1, “白雪公主”);

    g1.start();
    g2.start();
}

}

class Makeup extends Thread {

static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();

int choice; // 选择
String girlName; // 使用化妆品的人

Makeup(int choice, String girlName) {
    this.choice = choice;
    this.girlName = girlName;
}

@Override
public void run() {
    // 化妆
    try {
        makeup();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

// 化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
    if (choice == 0) {
        synchronized (lipstick) { // 获取口红的锁
            System.out.println(this.girlName + "获取口红的锁");
            Thread.sleep(1000);
            synchronized (mirror) { // 一秒钟后想获得镜子
                System.out.println(this.girlName + "想获得镜子的锁");
            }
        }
    } else {
        synchronized (mirror) { // 获取镜子的锁
            System.out.println(this.girlName + "获取镜子的锁");
            Thread.sleep(1000);
            synchronized (lipstick) { // 一秒钟后想获取口红
                System.out.println(this.girlName + "想获得口红的锁");
            }
        }
    }
}

}

// 口红
class Lipstick {}

// 镜子
class Mirror {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
执行结果
在这里插入图片描述
程序执行之后并不会结束,因为各自占着对方资源形成死锁。避免死锁要破坏死锁产生的四个必要条件。

线程池
线程池的定义以及方法
在这里插入图片描述
在这里插入图片描述
在一个应用程序中,我们需要多次使用线程,也就意味着,我们需要多次创建并销毁线程。而创建并销毁线程的过程势必会消耗内存。而在Java中,内存资源是及其宝贵的,所以,我们就提出了线程池的概念。

线程池:Java中开辟出了一种管理线程的概念,这个概念叫做线程池,从概念以及应用场景中,我们可以看出,线程池的好处,就是可以方便的管理线程,也可以减少内存的消耗。

创建一个线程池,Java中已经提供了创建线程池的一个类:Executor,一般使用它的子类:ThreadPoolExecutor。

public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
1
2
3
4
5
6
7
这是其中最重要的一个构造方法,这个方法决定了创建出来的线程池的各种属性,下面依靠一张图来更好的理解线程池和这几个参数:
在这里插入图片描述

corePoolSize 就是线程池中的核心线程数量,这几个核心线程,只是在没有用的时候,也不会被回收。
maximumPoolSize 就是线程池中可以容纳的最大线程的数量。
keepAliveTime 就是线程池中除了核心线程之外的其他的最长可以保留的时间,因为在线程池中,除了核心线程即使在无任务的情况下也不能被清除,其余的都是有存活时间的,意思就是非核心线程可以保留的最长的空闲时间。
util 就是计算这个时间的一个单位。
workQueue 就是等待队列,任务可以储存在任务队列中等待被执行,执行的是FIFIO原则(先进先出)。
threadFactory 就是创建线程的线程工厂。
handler 是一种拒绝策略,我们可以在任务满了之后,拒绝执行某些任务。
在这里插入图片描述
任务进来时,首先执行判断,判断核心线程是否处于空闲状态,如果不是,核心线程就先就执行任务,如果核心线程已满,则判断任务队列是否有地方存放该任务,若果有,就将任务保存在任务队列中,等待执行,如果满了,在判断最大可容纳的线程数,如果没有超出这个数量,就开创非核心线程执行任务,如果超出了,就调用handler实现拒绝策略。
handler的拒绝策略:

第一种abortpolicy:不执行新任务,直接抛出异常,提示线程池已满
第二种discardpolicy:不执行新任务,也不抛出异常
第三种discardoldestpolicy:将消息队列中的第一个任务替换为当前新进来的任务执行
第四种CallerRunsPolicy:直接调用execute来执行当前任务
常见线程池
newFixedThreadPool 定长线程池
一个有指定的线程数的线程池,有核心的线程,里面有固定的线程数量,响应的速度快。正规的并发线程,多用于服务器。固定的线程数由系统资源设置。核心线程是没有超时机制的,队列大小没有限制,除非线程池关闭了核心线程才会被回收。

newCachedThreadPool 可缓冲线程池
只有非核心线程,最大线程数很大,每新来一个任务,当没有空余线程的时候就会重新创建一个线程,这边有一个超时机制,当空闲的线程超过60s内没有用到的话,就会被回收,它可以一定程序减少频繁创建/销毁线程,减少系统开销,适用于执行时间短并且数量多的任务场景。

ScheduledThreadPool 周期线程池
创建一个定长线程池,支持定时及周期性任务执行,通过过schedule方法可以设置任务的周期执行

newSingleThreadExecutor 单任务线程池
创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行,每次任务到来后都会进入阻塞队列,然后按指定顺序执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值