Java多线程-2

部分代码:https://github.com/JiaZhengJingXianSheng/Java-Study-Notes/tree/main/java%E5%A4%9A%E7%BA%BF%E7%A8%8B


线程停止

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
// 测试线程停止
// 建议使用标志位
// 不建议使用 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) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main " + i);
if (i == 900) {
// 调用自定义stop 方法,切换标志位,让线程停止
testStop.stop();
System.out.println("线程停止");
}
}

}
}

线程休眠

Thread.sleep(int ms)


线程礼让

Thread.yield()


线程强制执行 join

thread.join() 其中thread是一个线程


同步方法和同步块

由于我们可以通过 private 关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法: synchronized 方法和 synchronized 块

synchronized方法控制对 “对象” 的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。

缺陷: 会影响效率


CopyOnWriteArrayList

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 测试 JUC 安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(
()->{
list.add(Thread.currentThread().getName());
}
).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}

死锁

死锁是指两个或两个以上的进程在执行过程中,由于竞争资源或者由于彼此通信而造成的一种阻塞的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁,这些永远在互相等待的进程称为死锁进程


Lock锁

显式锁

1
2
3
4
5
6
7
8
private final ReentrantLock lock = new ReentrantLock();
try{
lock.lock(); // 加锁
// 处理
}finally{
lock.unlock(); // 解锁
}

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
64
65
66
/**
* Created with IntelliJ IDEA
*
* @Author: LYZ
* @Date: 2022/03/09
*/

// 测试 Lock 锁
public class TestLock {

public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();

}
}

class TestLock2 implements Runnable{

int tickNums = 10;

// 定义 lock 锁
private final ReentrantLock lock = new ReentrantLock();

@Override
public void run() {
while(true){
try{
lock.lock();
if (tickNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(tickNums--);
}else{
break;
}
}finally {
lock.unlock();
}
}
}

// 未加锁
// @Override
// public void run() {
// while(true){
// if (tickNums>0){
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// System.out.println(tickNums--);
// }else{
// break;
// }
// }
// }
}

生产者消费者问题

生产者消费者问题,也称有限缓冲问题。生产者和消费者共享一个资源

对于生产者,没有生产产品之前,要通知消费者等待,而生产了产品之后,又要马上通知消费者消费。

对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费。

在生产者消费者问题中,仅有synchronized 是不够的

synchronized 可阻止并发更新同一个共享资源,实现了同步

synchronized 不能用来实现不同线程之间的消息传递(通信)

Java 提供了几个方法解决线程之间的通信问题

1
2
3
wait(); // 表示线程一直等待,与sleep不同,会释放锁。
notify(); // 唤醒一个处于等待状态的线程
notifyAll(); // 唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度。

解决方法一 (管程法)

  • 生产者:负责生产数据的模块

  • 消费者:负责处理数据的模块

  • 缓冲区:消费者不能直接使用生产者的数据,他们之间有个 “ 缓冲区 ”

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/**
* Created with IntelliJ IDEA
*
* @Author: LYZ
* @Date: 2022/03/09
*/

// 测试生产者-消费者模型 --> 利用缓冲区解决:管程法
// 生产者、消费者、产品、缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container= new SynContainer();
new Productor(container).start();
new Consumer(container).start();
new Consumer(container).start();
}
}

// 生产者
class Productor extends Thread {
SynContainer container;

public Productor(SynContainer container) {
this.container = container;
}

// 生产
@Override
public void run() {
// 生产 100 个产品
for (int i = 0; i < 200; i++) {

container.push(new Product(i));
System.out.println("生产了" + i + "个产品");
}
}
}

// 消费者
class Consumer extends Thread {
SynContainer container;

public Consumer(SynContainer container) {
this.container = container;
}

// 消费

@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了-->" + container.pop().id + "个产品");
}
}
}

// 产品
class Product {
int id; // 产品编号

public Product(int id) {
this.id = id;
}
}

// 缓冲区
class SynContainer {
// 需要一个容器大小
Product[] products = new Product[10];
// 容器计数器
int count = 0;

// 生产者放入产品
public synchronized void push(Product product) {
// 如果容器满了,等待消费者消费
// if语句中醒来的线程 不会再一次进行判断了 而while会重新再判断
while (count == products.length) {
// 通知消费者消费,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
// 如果没有满,生产产品
products[count] = product;
count++;


//可以通知消费者消费了
this.notifyAll();
}

// 消费者消费产品
public synchronized Product pop() {
// 判断能否消费
// if语句中醒来的线程 不会再一次进行判断了 而while会重新再判断
while (count <= 0) {
// 等待生产者生产
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// 如果可以消费
Product product = null;
if(count>0){
count--;
product = products[count];
}


// 吃完了,通知生产者生产
this.notifyAll();
return product;
}

}

解决方法二 (信号灯法)

设置标志位

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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Created with IntelliJ IDEA
*
* @Author: LYZ
* @Date: 2022/03/10
*/

// 测试生产者-消费者问题2: 信号灯法,设置标志位
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}

// 生产者 --> 演员
class Player extends Thread {
TV tv;

public Player(TV tv) {
this.tv = tv;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.tv.play("快乐大本营");
}
else{
this.tv.play("抖音:记录美好生活");
}
}
}
}

// 消费者 --> 观众
class Watcher extends Thread {
TV tv;

public Watcher(TV tv) {
this.tv = tv;
}

@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}

// 产品 --> 节目
class TV {
// 演员表演,观众等待
// 观众观看,演员等待
String voice; // 表演的节目
boolean flag = true;

// 表演
public synchronized void play(String voice) {
while (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("演员表演了" + voice);
// 通知观众观看
this.notifyAll(); // 唤醒
this.voice = voice;
this.flag = !this.flag;
}

// 观看
public synchronized void watch() {
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观众观看了" + voice);

// 通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}

线程池

如果并发的线程数量很多,并且每个线程都是执行一个时间很短的任务就结束了,这样频繁创建线程就会大大降低系统的效率,因为频繁创建线程和销毁线程需要时间。线程池可以实现复用。

**JDK 5.0 起提供了线程池相关的API :ExecutorService 和 Executors **

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
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* Created with IntelliJ IDEA
*
* @Author: LYZ
* @Date: 2022/03/11
*/

// 测试线程池
public class TestPool {
public static void main(String[] args) {
// 1. 创建线程池
// newFixedThreadPool 参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());

// 2. 关闭连接
service.shutdown();
}
}


class MyThread implements Runnable {

@Override
public void run() {

System.out.println(Thread.currentThread().getName());

}
}