这里使用ambda表达式(参数)->{代码}
首先是没有锁的情况下多个线程争夺同一个资源的情况
package com.zheng;
//线程就是一个单独的资源类
public class BuyTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
//并发:多线程操作同一个资源类,把资源类丢入线程
//lambda表达式(参数)->{代码}
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"C").start();
}
}
//资源类
class Ticket{
//属性和方法
private int num = 20;
public void sale(){
if(num > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(num--)+"票,剩余:"+num);
}
}
}
测试结果
公平锁:谁先来谁先执行
非公平锁:可以插队(默认)
加锁后
package com.zheng;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
//线程就是一个单独的资源类
public class BuyTicket {
public static void main(String[] args) {
Ticket ticket = new Ticket();
//并发:多线程操作同一个资源类,把资源类丢入线程
//lambda表达式(参数)->{代码}
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 30; i++) {
ticket.sale();
}
},"C").start();
}
}
//资源类
class Ticket{
//属性和方法
private int num = 20;
Lock lock = new ReentrantLock();
public void sale(){
lock.lock();//加锁
try {
//业务代码
if(num > 0){
System.out.println(Thread.currentThread().getName()+"卖出了"+(num--)+"票,剩余:"+num);
}
} catch (Exception e) {
lock.unlock();
}
}
}