标签:lse err [] tac new ati com bre imp
package com.hls.juc;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 解决多线程安全问题的方式: 3种
* synchronized: 隐式锁
* 1. 同步方法
* 2. 同步代码块
*
* 3.Lock同步锁: 显示锁 可以更加灵活的控制同步的代码访问
* 注意 : 必须 显示上锁 lock() 必须在finally块中释放锁unlock()
*
*/
public class LockTask {
public static void main(String[] args) {
TicketTask ticketTask = new TicketTask();
new Thread(ticketTask, "1号窗口").start();
new Thread(ticketTask, "2号窗口").start();
new Thread(ticketTask, "3号窗口").start();
}
}
class TicketTask implements Runnable{
private int ticket = 10;
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true){
lock.lock();
try {
if(ticket > 0){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "已售票, 余票" + --ticket);
} catch (Exception e) {
e.printStackTrace();
}
}else {
break;
}
} finally {
//务必在finally块中释放锁
lock.unlock();
}
}
}
}
标签:lse err [] tac new ati com bre imp
原文地址:https://www.cnblogs.com/huangleshu/p/10029116.html