import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TicketDemo {
public static void main(String[] args) {
Ticket ticket=new Ticket(40);
new Thread(()->{
for (int i = 0; i <20 ; i++) {
ticket.sell();
}
},"a").start();
new Thread(()->{
for (int i = 0; i <20 ; i++) {
ticket.sell();
}
},"b").start();
new Thread(()->{
for (int i = 0; i <20 ; i++) {
ticket.sell();
}
},"c").start();
}
}
class Ticket{
private int num;
private Lock lock=new ReentrantLock();
public Ticket(int num) {
this.num = num;
}
/**
* sychronized方法
*/
/*public synchronized void sell(){
if(num>0){
num--;
System.out.println(Thread.currentThread().getName()+" remain:"+num);
}
}*/
/**
* sychronized代码块
*/
/*public void sell(){
if(num<=0){
return;
}
synchronized (this){
if(num>0){
num--;
System.out.println(Thread.currentThread().getName()+" remain:"+num);
}
}
}*/
/**
* lock
*/
public void sell(){
lock.lock();
try {
if(num>0){
num--;
System.out.println(Thread.currentThread().getName()+" remain:"+num);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
Java_多线程_sychronized方法、sychronized代码块、Lock接口模拟售票
最新推荐文章于 2024-03-22 04:31:46 发布