-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathSyncDemo.java
82 lines (67 loc) · 1.58 KB
/
SyncDemo.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
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
78
79
80
81
82
/*
* @(#)SyncDemo.java $version 2011. 11. 16.
*
* Copyright 2007 NHN Corp. All rights Reserved.
* NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package study.javacon;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* @author benelog
*/
public class SyncDemo {
/**
* @param args
*/
public static void main(String[] args) {
Object lock = new Object();
Object lock2 = new Object();
ExecutorService pool = Executors.newSingleThreadExecutor();
pool.execute(new Walker("A walker",lock));
pool.execute(new Walker("B walker",lock));
pool.execute(new Walker("C walker",lock));
pool.shutdown();
}
static class Walker implements Runnable {
private String name;
private Object lock;
public Walker(String name, Object lock){
this.name = name;
this.lock = lock;
}
/**
*
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
moveStep(name,1);
moveStep(name,2);
moveStep(name,3);
synchronized (lock) {
System.out.println(name + " : start sync block");
moveStep(name,4);
moveStep(name,5);
moveStep(name,6);
System.out.println(name + ": end sync block");
}
moveStep(name,7);
moveStep(name,8);
moveStep(name,9);
}
/**
* @param name2
* @param i
*/
private void moveStep(String name, int i) {
System.out.printf("%s, %d\n",name,i);
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
}
}