线程同步锁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

class AccountingSync implements Runnable {
static AccountingSync instance = new AccountingSync();
static int i = 0;

@Override
public void run() {
//省略其他耗时操作....
while (true) {
synchronized (AccountingSync.class) {
if (i < 100) {
i++;
System.out.println(Thread.currentThread().getName() + " "+ i);
}
}
}
}

}

class test {
public static void main(String[] args) {
AccountingSync accountingSync = new AccountingSync();
Thread t1 = new Thread(accountingSync);
Thread t2 = new Thread(accountingSync);
t1.start();
t2.start();
}
}