一.售票案例
1.传统synchronized实现
package com.yu.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test2 {
public static void main(String[] args) {
Ticked ticked = new Ticked();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked.ticked();},"A").start();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked.ticked();},"B").start();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked.ticked();},"C").start();
}
}
//传统synchronized锁
class Ticked{
private int sum = 30;
//卖票
public synchronized void ticked(){
if(sum>0){
System.out.println(Thread.currentThread().getName()+"卖出第"+(sum--)+"张票,还剩"+sum+"张票");
}
}
}
2.Lock实现
package com.yu.lock;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test2 {
public static void main(String[] args) {
Ticked2 ticked2 = new Ticked2();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked2.ticked();},"A").start();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked2.ticked();},"B").start();
new Thread(()->{for (int i = 0; i <40 ; i++)ticked2.ticked();},"C").start();
}
}
//JUC--Lock锁
class Ticked2{
private int sum = 30;
Lock lock = new ReentrantLock();//获取Lock锁
public void ticked(){
lock.lock();//加锁
try {
if(sum>0){
System.out.println(Thread.currentThread().getName()+"卖出第"+(sum--)+"张票,还剩"+sum+"张票");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
lock.unlock();//解锁
}
}
}
Lock接口的实现类
ReentrantLock:可重入锁(常用)--默认为非公平锁
ReentrantReadWriteLock.ReadLock:读锁
ReentrantReadWriteLock.WriteLock:写锁
公平锁:十分公平,先来后到。
非公平锁:十分不公平,可以插队。
二.Synchronized和Lock的区别
1.Synchronized是内置的Java关键字,Lock是Java的一个接口
2.Synchronized无法判断锁的状态,Lock可以判断是否获取到了锁
3.Synchronized会自动释放锁,Lock必须手动释放锁,否则会死锁
4.Synchronized 线程1(获得锁,阻塞),线程2(等待,傻傻的等),Lock锁不一定会等下去
5.Synchronized可重入锁,不可以中断,非公平,Lock锁,可重入锁,可以判断锁,非公平(可以自己设置)
6.Synchronized适合锁少量的代码同步问题,Lock适合锁大量的同步代码块
三.生产者,消费者问题
1.Synchronized版
package com.yu.lock;
//生产者消费者问题
/**
* A B 线程交替执行操作同一个sum
* A sum+1
* B sum-1
*/
public class Test3 {
public static void main(String[] args) {
Date date = new Date();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "D").start();
}
}
//传统消费者,生产者问题
class Date{
private int sum = 0;
public synchronized void number1() throws InterruptedException {
if(sum!=0){//线程等待
this.wait();
}
sum++;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
this.notifyAll();//通知其他线程
}
public synchronized void number2() throws InterruptedException {
if(sum==0){//线程等待
this.wait();
}
sum--;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
this.notifyAll();//通知其他线程
}
}
发现运行后的结果并不是我们想要的,其实这是出现了虚假唤醒,简单的来说就是线程可以唤醒,但不会被通知,中断或超时。所以需要将if判断改为while判断,就可以解决虚假唤醒问题
package com.yu.lock;
//生产者消费者问题
/**
* A B 线程交替执行操作同一个sum
* A sum+1
* B sum-1
*/
public class Test3 {
public static void main(String[] args) {
Date date = new Date();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "C").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
date.number2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "D").start();
}
}
//传统消费者,生产者问题
class Date{
private int sum = 0;
/**
* 使用if判断会发生虚假唤醒,将if改为while即可
*/
public synchronized void number1() throws InterruptedException {
while(sum!=0){//线程等待
this.wait();
}
sum++;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
this.notifyAll();//通知其他线程
}
public synchronized void number2() throws InterruptedException {
while(sum==0){//线程等待
this.wait();
}
sum--;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
this.notifyAll();//通知其他线程
}
}
2.Lock版
package com.yu.lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test4 {
public static void main(String[] args) {
Date2 date2 = new Date2();
new Thread(()->{for (int i = 0; i < 10; i++) {date2.number1();}},"A").start();
new Thread(()->{for (int i = 0; i < 10; i++) {date2.number2();}},"B").start();
}
}
class Date2{
private int sum = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void number1() {
lock.lock();
while (sum!=0){
try {
condition.await();//等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sum++;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
//通知其他线程
condition.signalAll();//唤醒全部
lock.unlock();
}
public void number2() {
lock.lock();
while (sum==0){
//等待
try {
condition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
sum--;
System.out.println(Thread.currentThread().getName()+"=>"+sum);
//通知其他线程
condition.signalAll();
lock.unlock();
}
}
这是时候可能有人会有疑问,Synchronized和Lock完成的都是一样的内容,何必要有Lock接口呢,要明白,任何一种新的技术,绝对不是仅仅覆盖原来的技术,一定会有优势或补充。
四.Condition的精准通知与唤醒
package com.yu.lock;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test5 {
public static void main(String[] args) {
Date3 date3 = new Date3();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
date3.print1();
}
},"A").start();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
date3.print2();
}
},"B").start();
new Thread(()->{
for (int i = 0; i <10 ; i++) {
date3.print3();
}
},"C").start();
}
}
class Date3 {
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
private int num = 1;
public void print1() {
lock.lock();
try {
while (num != 1) {
condition1.await();//A等待
}
System.out.println(Thread.currentThread().getName()+"=>"+num);
num++;
condition2.signal();//B唤醒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print2() {
lock.lock();
try {
while (num!=2){
condition2.await();//B等待
}
System.out.println(Thread.currentThread().getName()+"=>"+num);
num++;
condition3.signal();//C唤醒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void print3() {
lock.lock();
try {
while (num!=3){
condition3.await();//C等待
}
System.out.println(Thread.currentThread().getName()+"=>"+num);
num=1;
condition1.signal();//A唤醒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
五.8锁现象
判断Synchronized锁到底锁的是什么!
案例描述:有一个phone类,并实现的打电话和短信两个方法,方法都用Synchronized修饰,创建两个线程,分别运行打电话和发短信的方法,先执行发短信,并使程序sleep一秒,再执行打电话方法,判断先运行那个线程。
1.标准情况下,两个线程先打印发短信还是打电话?
2.发短信方法延迟4秒执行,两个线程先打印发短信还是打电话?
package com.yu.lock8;
//锁的8个问题
//1.标准情况下,先打印发短信还是打电话---发短信
//2.发短信延迟4秒,先打印发短信还是打电话---发短信
/**
* 因为synchronized锁的对象是方法的调用者
* 两个方法用的是同一个锁,谁先拿到谁先执行
*/
import java.util.concurrent.TimeUnit;
public class Test1 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(()->{phone.sendSms();},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{phone.call();},"B").start();
}
}
class Phone{
public synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call(){
System.out.println("打电话");
}
}
3.增加了一个普通方法后!先执行发短信还是普通方法?
4.两个对象,两个同步方法,两个线程先打印发短信还是打电话?
package com.yu.lock8;
import java.util.concurrent.TimeUnit;
//3.增加一个普通方法,先发短信还是hello--hello
//4.两个对象,两个同步方法,先打印发短信还是打电话---打电话
/**
* 因为普通方法没有锁,不是同步方法
* 锁的不是同一个实例对象,所以先执行打电话
*/
public class Test2 {
public static void main(String[] args) {
Phone1 phone1 = new Phone1();
Phone1 phone2 = new Phone1();
new Thread(()->{phone1.sendSms();},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{phone2.call();},"B").start();
//new Thread(()->{phone.hello();},"C").start();
}
}
class Phone1{
public synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call(){
System.out.println("打电话");
}
//public void hello(){
// System.out.println("hello");
//}
}
5.增加两个静态的同步方法,只有一个对象,两个线程先打印发短信还是打电话?
6.两个对象!两个静态同步方法,两个线程先打印发短信还是打电话?
package com.yu.lock8;
import java.util.concurrent.TimeUnit;
//5.增加两个静态同步方法。只有一个对象,先执行发短信还是打电话--发短信
//5.增加两个静态同步方法。有两个对象,先执行发短信还是打电话--发短信
/**
* 静态同步方法,类一加载就有了,锁的是Class模板,并不是锁的实例对象。
* 两个对象的Class模板只有一个,
*/
public class Test3 {
public static void main(String[] args) {
Phone2 phone1 = new Phone2();
Phone2 phone2 = new Phone2();
new Thread(()->{phone1.sendSms();},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{phone2.call();},"B").start();
//new Thread(()->{phone.hello();},"C").start();
}
}
class Phone2{
public static synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public static synchronized void call(){
System.out.println("打电话");
}
//public void hello(){
// System.out.println("hello");
//}
}
7.一个静态同步方法,一个普通同步方法,一个对象,两个线程先打印发短信还是打电话?
8.一个静态同步方法,一个普通同步方法,两个对象,两个线程先打印发短信还是打电话?
package com.yu.lock8;
import java.util.concurrent.TimeUnit;
//一个静态同步方法,一个普通同步方法,一个对象,先打印发短信还是打电话---打电话
//一个静态同步方法,一个普通同步方法,两个对象,先打印发短信还是打电话---打电话
/**
* 静态同步方法锁的是Class模板,普通同步方法锁的是方法的调用对象
* */
public class Test4 {
public static void main(String[] args) {
Phone3 phone1 = new Phone3();
Phone3 phone2 = new Phone3();
new Thread(()->{phone1.sendSms();},"A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{phone2.call();},"B").start();
//new Thread(()->{phone.hello();},"C").start();
}
}
class Phone3{
public static synchronized void sendSms(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("发短信");
}
public synchronized void call(){
System.out.println("打电话");
}
//public void hello(){
// System.out.println("hello");
//}
}
结论 :1.Synchronized锁的对象是方法的调用者
2.static 静态方法,与类一起加载,Synchronized锁的是Class。