请大家帮忙看看这段代码中 synchronized 为什么没有起作用。
锁添加的是类级别的,为什么锁没有起作用,两个线程都可以访问。
public class AccountingSync implements Runnable{
int i =0;
//Integer k = 0;
static Integer sk = 0;
public void increase(){
System.out.println(Thread.currentThread().getName() + " before " + i);
i++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " after " + i);
}
@Override
public void run() {
for (int j =0; j< 10; j++){
synchronized (sk){
increase();
}
}
}
public static void main(String[] args) {
AccountingSync instance = new AccountingSync();
AccountingSync instance1 = new AccountingSync();
Thread t1 = new Thread(instance);
Thread t2 = new Thread(instance1);
t1.start();
t2.start();
// System.out.println(i);
}
}
运行结果及报错内容
Thread-0 before 0
Thread-0 after 1
Thread-1 before 0
Thread-1 after 1
Thread-1 before 1
Thread-1 after 2
Thread-1 before 2
Thread-1 after 3
Thread-1 before 3
Thread-1 after 4
Thread-1 before 4
Thread-1 after 5
Thread-1 before 5
Thread-1 after 6
Thread-1 before 6
Thread-1 after 7
Thread-1 before 7
Thread-1 after 8
Thread-1 before 8
Thread-1 after 9
Thread-0 before 1
Thread-0 after 2
Thread-1 before 9
Thread-1 after 10
Thread-0 before 2
Thread-0 after 3
Thread-0 before 3
Thread-0 after 4
Thread-0 before 4
Thread-0 after 5
Thread-0 before 5
Thread-0 after 6
Thread-0 before 6
Thread-0 after 7
Thread-0 before 7
Thread-0 after 8
Thread-0 before 8
Thread-0 after 9
Thread-0 before 9
Thread-0 after 10
我的解答思路和尝试过的方法
我想要达到的结果
Thread-0 before 0
Thread-0 after 1
Thread-0 before 1
Thread-0 after 2
Thread-0 before 2
Thread-0 after 3
Thread-0 before 3
Thread-0 after 4
Thread-1 before 4
Thread-1 after 5
Thread-1 before 5
Thread-1 after 6
Thread-1 before 6
Thread-1 after 7
Thread-1 before 7
Thread-1 after 8
Thread-1 before 8
Thread-1 after 9
Thread-0 before 9
Thread-0 after 10
Thread-1 before 10
Thread-1 after 11
Thread-1 before 11
Thread-1 after 12
Thread-1 before 12
Thread-1 after 13
Thread-1 before 13
Thread-1 after 14
Thread-1 before 14
Thread-1 after 15
Thread-0 before 15
Thread-0 after 16
Thread-0 before 16
Thread-0 after 17
Thread-0 before 17
Thread-0 after 18
Thread-0 before 18
Thread-0 after 19
Thread-0 before 19
Thread-0 after 20