完美解决Java中的线程安全问题

2025-05-29 0 95

给出一个问题,如下:

完美解决Java中的线程安全问题

解决方案如下:

?

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
public class Demo_5 {

public static void main(String[] args) {

//创建一个窗口

TicketWindow tw1=new TicketWindow();

//使用三个线程同时启动

Thread t1=new Thread(tw1);

Thread t2=new Thread(tw1);

Thread t3=new Thread(tw1);

t1.start();

t2.start();

t3.start();

}

}

//售票窗口类

class TicketWindow implements Runnable{

private int nums=2000; //一共2000张票

@Override

public void run() {

while(true){

if(nums>0){ //先判断是否还有票

//Thread.currentThread().getName()得到当前线程的名字

System.out.println(Thread.currentThread().getName()+"在售出第"+nums+"张票"); //显示售票信息

//出票的速度是一秒出一张

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

nums--;

}else{

break; //售票结束

}

}

}

}

执行这段代码发现问题,就是同一张票号可能被多个售票窗口出售,惹祸的代码就是if else语句块。

解决方法就是在需要同步的代码段用synchronized(Object){你要同步的代码}即可。

修改后代码如下:

?

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
public class Demo_5 {

public static void main(String[] args) {

//创建一个窗口

TicketWindow tw1=new TicketWindow();

//使用三个线程同时启动

Thread t1=new Thread(tw1);

Thread t2=new Thread(tw1);

Thread t3=new Thread(tw1);

t1.start();

t2.start();

t3.start();

}

}

//售票窗口类

class TicketWindow implements Runnable{

private int nums=2000; //一共2000张票

@Override

public void run() {

while(true){

//认为if else这段代码要保证其原子性(同步代码块)

synchronized (this) {

if(nums>0){ //先判断是否还有票

//Thread.currentThread().getName()得到当前线程的名字

System.out.println(Thread.currentThread().getName()+"在售出第"+nums+"张票"); //显示售票信息

//出票的速度是一秒出一张

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

nums--;

}else{

break; //售票结束

}

}

}

}

}

执行这段代码发现出票正常了。

线程1正执行需要做同步处理的代码,线程2,3,4……blocked,被放入了线程等待池,就好像某人上厕所前先把门关上(上锁),完事之后再出来(解锁),然后别人就可以继续使用了。

以上这篇完美解决Java中的线程安全问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 完美解决Java中的线程安全问题 https://www.kuaiidc.com/115253.html

相关文章

发表评论
暂无评论