1、Lock
- Lock类同样可达到synchronized效果,且在使用上比synchronized更加灵活
- Lock lock = new ReentrantLock();
- 加锁:lock.lock();
- 解锁:lock.unlock(); ``` public class Main { public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
new Thread(runnable, "SyncThread1").start();
new Thread(runnable, "SyncThread2").start();
/**
SyncThread1:0
SyncThread1:1
SyncThread1:2
SyncThread1:3
SyncThread1:4
SyncThread2:5
SyncThread2:6
SyncThread2:7
SyncThread2:8
SyncThread2:9
*/
}
static class MyRunnable implements Runnable {
public static int count;
private Lock lock = new ReentrantLock();
public MyRunnable() {
count = 0;
}
public void run() {
// 此处锁的是MyRunnable对象
lock.lock();
try {
for (int i = 0; i < 5; i++) {
try {
System.out.println(Thread.currentThread().getName() + ":" + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} finally {
lock.unlock();
}
}
}
} ```