浅析Java多线程同步synchronized

2025-05-29 0 78

单线程是安全的,因为线程只有一个,不存在多个线程抢夺同一个资源

代码例子:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
public class SingleThread {

int num=10;

public void add(){

while(num<13){

num++;

try{

Thread.sleep(1000);

}

catch(Exception e){

System.out.println("中断");

}

System.out.println(num);

}

}

public static void main(String[] args){

Thread thread = Thread.currentThread(); //获取当前运行的线程对象

thread.setName("单线程"); //线程重命名

System.out.println(thread.getName()+"正在运行");

SingleThread st=new SingleThread();

st.add();

}

}

多线程安全,synchronized同步代码块

synchronized(对象){}; //同步代码块

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
class One {

int num=10;

public void add(){

synchronized(this){ //同步代码块,同步方法也可以实现效果synchronized void add(){};

num++;

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

System.out.println("中断");

}

System.out.println(num);

}

}

}

class Two implements Runnable{

One one = new One();

@Override

public void run() {

one.add(); //调用add方法

}

}

public class Synch{

public static void main(String[] args) {

Two two = new Two();

Thread t1 = new Thread(two); //创建三个子线程

Thread t2 = new Thread(two);

Thread t3 = new Thread(two);

t1.start();

t2.start();

t3.start();

}

}

注意:观察去除synchronized关键字的运行结果区别!

正常运行结果:

11
12
13

原文链接:https://www.idaobin.com/archives/839.html

收藏 (0) 打赏

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

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

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

快网idc优惠网 建站教程 浅析Java多线程同步synchronized https://www.kuaiidc.com/112433.html

相关文章

发表评论
暂无评论