码迷,mamicode.com
首页 > 其他好文 > 详细

并发编程

时间:2020-02-09 11:44:58      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:rgs   public   代码   class   tst   cep   com   静态   tar   

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
36
37
38
39
40
41
public class MultiThread{

private static int num=0;

public synchronized void printNum(String tag){
try{
if(tag.equals("a")){

num=100;
System.out.println("tag a,set num over");
Thread.sleep(1000);
}else{
num=200;
System.out.println("tag b,set num over");
}
System.out.println("tag"+tag+",num="+num);
}catch(InterruptedException e){
e.printStackTrace();
}
}

public static void main(String[] args){
final MultiThread m1=new MultiThread();
final MultiThread m2=new MultiThread();

Thread t1=new Thread(new Runnable(){
public void run(){
m1.printNum("a");
}
大专栏  并发编程 });

Thread t2=new Thread(new Runnable(){
public void run(){
m2.printNum("b");
}
});

t1.start();
t2.start();
}
}

程序输出的结果:

1
2
3
4
tag a,set num over
tag b,set num over
tagb,num=200
taga,num=200

其实此时程序会出现两种结果的输出:

1
2
3
4
tag b,set num over
tag a,set num over
tagb,num=100
taga,num=100

1
2
3
4
tag b,set num over
tag a,set num over
tagb,num=200
taga,num=200

这是因为int num 被static 修饰,当线程t1和t2的执行顺序不同的时候就会出现这两种结果。此时synchronized是否修饰都不影响程序的执行效果,去掉static 关键字再来观察。

1
2
3
4
tag a,set num over
tag b,set num over
tagb,num=200
taga,num=100

两次输出的结果并不相同,各自输出了各自的预期输出值。线程之间并没有受到干扰。再synchronzied关键字前加上static ,这样便成为了类锁,整个他t1,t2中的printnum方法会存在抢占,会先执行完其一,再执行另一个,看输出结果。

1
2
3
4
tag b,set num over
tagb,num=200
tag a,set num over
taga,num=100

并发编程

标签:rgs   public   代码   class   tst   cep   com   静态   tar   

原文地址:https://www.cnblogs.com/lijianming180/p/12286277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!