synchronized和Lock的区别
1.synchronized是内置的java关键字,Lock是java类
2.synchronized无法判断获取锁的状态,Lock可以判断获取锁的状 态。
3.synchronized会自动释放锁,lock要手动释放,如果不释放就会死 锁。
4.synchronized线程1(获得锁、阻塞)、线程2(等待、傻傻等待);lock锁不一定会等待下去。 lock.tryLock()尝试获取锁
5. synchronized适合少量代码同步,Lock适合大量代码同步。
(Lock灵活度搞)
**一:synchronized(传统方式)
public class TestSell {
public static void main(String[] args) {
Ticket ticket=new Ticket();
new Thread(new Runnable() {
@Override
public void run() {
ticket.sell();
}
},"111").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20000; i++) {
ticket.sell();
}
}
},"111").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20000; i++) {
ticket.sell();
}
}
},"222").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 20000; i++) {
ticket.sell();
}
}
},"333").start();
// new Thread(()->{
// for (int i = 0; i < 12000; i++) {
// ticket.sell();
// }
// },"AA").start();
//
// new Thread(()->{
// for (int i = 0; i < 12000; i++) {
// ticket.sell();
// }
// },"bb").start();
//
// new Thread(()->{
// for (int i = 0; i < 12000; i++) {
// ticket.sell();
// }
// },"cc").start();
}
}
class Ticket{
private int count =10000;
public synchronized void sell(){
if (count>0){
System.out.println(Thread.currentThread().getName()+"买了第"+count+"张票==========");
count--;
}
}
}
一:synchronized(armda表达式方式)**
public class TestSell {
public static void main(String[] args) {
Ticket ticket=new Ticket();
new Thread(()->{
for (int i = 0; i < 12000; i++) {
ticket.sell();
}
},"AA").start();
new Thread(()->{
for (int i = 0; i < 12000; i++) {
ticket.sell();
}
},"bb").start();
new Thread(()->{
for (int i = 0; i < 12000; i++) {
ticket.sell();
}
},"cc").start();
}
}
class Ticket{
private int count =10000;
public synchronized void sell(){
if (count>0){
System.out.println(Thread.currentThread().getName()+"买了第"+count+"张票==========");
count--;
}
}
}
二:Lock锁
public class LockTest {
public static void main(String[] args) {
Ticket ticket = new Ticket();
new Thread(() -> { for (int i = 0; i < 12000; i++) ticket.sell(); }, "111").start();
new Thread(() -> { for (int i = 0; i < 12000; i++) ticket.sell(); }, "222").start();
new Thread(() -> { for (int i = 0; i < 12000; i++) ticket.sell(); }, "333").start();
}
}
class Ticket{
private int count =10000;
Lock lock=new ReentrantLock();
public void sell(){
lock.lock();
try {
if (count>0) System.out.println(Thread.currentThread().getName()+"买了第"+count+"张票==========");
count--;
}
finally {
lock.unlock();
}
}
}