并发编程之买票问题
作者:互联网
这里使用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();
}
}
}
标签:Thread,int,编程,sale,并发,num,new,买票,ticket 来源: https://blog.csdn.net/weixin_43304253/article/details/122157088