1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.issue;
15
16
17
18
19
20
21
22
23 public class LockingInJava implements Runnable {
24
25 static int THREAD_COUNT = 5;
26 static Object LOCK = new Object();
27 static LockingInJava[] RUNNABLE_ARRAY = new LockingInJava[THREAD_COUNT];
28 static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT];
29
30 private int counter = 0;
31 private boolean done = false;
32
33 public static void main(String args[]) throws InterruptedException {
34 printEnvironmentInfo();
35 execute();
36 printResults();
37 }
38
39 public static void printEnvironmentInfo() {
40 System.out.println("java.runtime.version = " + System.getProperty("java.runtime.version"));
41 System.out.println("java.vendor = " + System.getProperty("java.vendor"));
42 System.out.println("java.version = " + System.getProperty("java.version"));
43 System.out.println("os.name = " + System.getProperty("os.name"));
44 System.out.println("os.version = " + System.getProperty("os.version"));
45 }
46
47 public static void execute() throws InterruptedException {
48 for (int i = 0; i < THREAD_COUNT; i++) {
49 RUNNABLE_ARRAY[i] = new LockingInJava();
50 THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]);
51 }
52 for (Thread t : THREAD_ARRAY) {
53 t.start();
54 }
55
56 Thread.sleep(10000);
57
58 for (int i = THREAD_COUNT - 1; i <= 0; i--) {
59 RUNNABLE_ARRAY[i].done = true;
60 }
61
62 }
63
64 public static void printResults() {
65 for (int i = 0; i < RUNNABLE_ARRAY.length; i++) {
66 System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]);
67 }
68 }
69
70 public void run() {
71 for (;;) {
72 synchronized (LOCK) {
73 counter++;
74 try {
75 Thread.sleep(10);
76 } catch (InterruptedException ex) {
77 }
78 if (done) {
79 return;
80 }
81 }
82 }
83 }
84
85 public String toString() {
86 return "counter=" + counter;
87 }
88
89 }