# synchronized和lock的区别
- synchronized是java内置的关键字,lock是一个java类。
- synchronized无法获取锁的状态,Lock可判断锁的状态。
- synchronized会自动释放锁,但是lock需要手动来释放锁。
- synchronized释放锁(一、线程同步代码块执行完释放锁,二、线程异常释放锁)。
- 用synchronized锁A和B两个线程,如果,A线程拿到锁,那么B线程则等待,如果线程A阻塞那么B线程一直等待。用lock锁A和B两个线程的话,B线程如果一直拿不到锁就会结束等待。
- synchronized的锁可重入、不可中断、非公平。lock可重复、默认为非公平,构造方法可以传入boolean 值,true为公平锁,false为非公平锁。
- synchronized适合少量的同步代码块,lock适合锁大量的同步代码块。
synchronized示例
public class TestSynchronized {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i <= 5;i++){
ticket.saleTick();
}
}
}, "a").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i <= 5;i++){
ticket.saleTick();
}
}
},"b").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i <= 5;i++){
ticket.saleTick();
}
}
},"c").start();
}
}
class Ticket{
private int ticketNums = 10;
public synchronized void saleTick(){
if (ticketNums > 0){
System.out.println(Thread.currentThread().getName() + "买的第" + ticketNums + "张票");
ticketNums--;
}
}
}
执行结果
如果不加synchronized就会发生异常
lock示例
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(()->{
for (int i = 0;i <5 ; i++){
ticket.saleTick();
}
},"a").start();
new Thread(()->{
for (int i = 0;i <5 ; i++){
ticket.saleTick();
}
},"b").start();
new Thread(()->{
for (int i = 0;i <5 ; i++){
ticket.saleTick();
}
},"c").start();
}
}
class Ticket{
private int ticketNum = 10;
private Lock lock =new ReentrantLock();
public void saleTick(){
lock.lock();
try {
if (ticketNum > 0){
System.out.println(Thread.currentThread().getName() + "买的第" + ticketNum + "张票" );
ticketNum--;
}
} catch (Exception e){
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
执行结果: