package com.homework;
import java.util.concurrent.locks.ReentrantLock;
class Ticket implements Runnable{
int count=3;
ReentrantLock rt=new ReentrantLock(); //第三种方法,显示加锁,效率最高
Object obj=new Object(); //第一种方法.同步代码块,加监视器,监视器是一个共享的对象
@Override
public /*synchronized*/ void run() {//第二种方法,同步方法,效率低一点
// synchronized(obj) {
rt.lock(); //加锁
if(count>0) {
System.out.println(Thread.currentThread().getName()+"买到了,还剩"+count);
count --;
}
rt.unlock(); //解锁
// }
}
}
public class TicketDmeo {
public static void main(String[] args) throws Exception {
Ticket td = new Ticket();
Thread t1=new Thread(td,"一号");
t1.start();
//Thread.yield();
Thread t2=new Thread(td,"二号");
t2.start();
//Thread.yield();
Thread t3=new Thread(td,"三号");
t3.start();
//Thread.yield();
Thread t4=new Thread(td,"四号");
t4.start();
//Thread.yield();
Thread t5=new Thread(td,"五号");
t5.start();
}
}
java多线程之三种同步方法实现抢火车票
最新推荐文章于 2024-07-10 02:57:27 发布