java JUC基础学习
程序员文章站
2022-04-15 18:25:33
package geovis.demo;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;class Tiket { private Integer number = 68; //Lock实现提供比使用synchronized方法和语句可以获得的更广泛的锁定操作。 Lock lock = new ReentrantLock(); public....
本学习笔记内容来自尚硅谷周阳老师:
package geovis.demo;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Tiket {
private Integer number = 68;
//Lock实现提供比使用synchronized方法和语句可以获得的更广泛的锁定操作。
Lock lock = new ReentrantLock();
public void sail(){
//lock标准使用方法为lock.lock();try{}catch{}finally{lock.unlock()}
lock.lock();
try {
if(number > 0)
System.out.println(Thread.currentThread().getName() + "卖出去第:" + (number--) + "张票" + "还剩:" + number + "张。");
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class Jucdemo {
public static void main(String[] args) {
System.out.println("开启java多线程学习");
Tiket tiket = new Tiket();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0;i < 70;i++){
tiket.sail();
}
}
},"张三").start();
new Thread(()->{for (int i=0;i<70;i++) tiket.sail();},"蓝不大").start();
}
}
本文地址:https://blog.csdn.net/wuxiaowu123/article/details/110087096
下一篇: 数据类型之队列的自我总结