线程的同步

线程的同步

当多个线程访问同一个对象的时候 (并发),并且某些线程还想修改这个对象,此时就需要线程同步。线程同步实质上是一种等待机制,多个需要访问此对象的线程进入这个对象的线程等待池,等前一个线程使用完毕,后一个线程才能开始访问。

线程同步的解决措施:锁机制

由于一个进程内的多个线程共享一块存储空间,为了保证数据的正确性,并发的同时加入锁机制synchronized,当一个线程获取到锁的时候,其他线程必须等待,使用和释放锁即可。

线程的三个不安全实例:

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
//不安全的买票机制
package demo.study.syn;

public class UnsafeBuyTickets {
public static void main(String[] args) {
Buytickets station = new Buytickets();
new Thread(station,"小明").start();
new Thread(station,"小红").start();
new Thread(station,"黄牛").start();
}

}

class Buytickets implements Runnable{
private int ticketNum = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void buy() throws InterruptedException {
if (this.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
//不安全的银行取钱机制
package demo.study.syn;

public class UnsafeBuyTickets {
public static void main(String[] args) {
Buytickets station = new Buytickets();
new Thread(station,"小明").start();
new Thread(station,"小红").start();
new Thread(station,"黄牛").start();
}

}

class Buytickets implements Runnable{
private int ticketNum = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void buy() throws InterruptedException {
if (this.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
//不安全的数组
package demo.study.syn;

import java.util.ArrayList;
import java.util.List;

public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
-------------本文结束感谢您的阅读-------------