传统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
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
package cn.itcast.heima2;

public class TraditionalThreadSynchronized {

/**
* @param args
*/
public static void main(String[] args) {
new TraditionalThreadSynchronized().init();
}

private void init(){//todo 如果在不使用outputer时,是线程不安全的,打印时会出现串行的情况
final Outputer outputer = new Outputer();
new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output("zhangxiaoxiang");//todo 与下面的比较
}

}
}).start();

new Thread(new Runnable(){
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputer.output2("lihuoming");//todo 与上面的比较
}

}
}).start();

}

static class Outputer{

public void output(String name){
int len = name.length();
synchronized (this) //todo 代码块的锁闩为Outputer.class时可以和方法3互斥,在this的情况下只能和方法2互斥
{
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}

public synchronized void output2(String name){ //todo 方法
int len = name.length();
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}

public static synchronized void output3(String name){ //todo 静态方法
int len = name.length();
for(int i=0;i<len;i++){
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}