public class Lock02 {
private int i = 0;
public static void main(String[] args) {
Object o = new Object();
Lock02 lock = new Lock02();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (o) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100; i++) {
synchronized (o) {
lock.i++;
String name = Thread.currentThread().getName();
System.out.println(lock.i +" :: "+ name);
}
}
}).start();
}
}
这是对象锁的测试 为什么打印结果竟然是交错的
1 :: Thread-0
2 :: Thread-0
3 :: Thread-1
4 :: Thread-1
5 :: Thread-1
6 :: Thread-1
7 :: Thread-1
不是获取一个对象锁 方法不执行完 锁不释放吗 这里好像是锁释放了??? 为什么会这样
【软文代发】多线程 对象锁的问题
最新推荐文章于 2024-08-09 15:44:46 发布