package com.dongmu.test;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Test01 {
public static void main(String[] args) {
/*获得CPU的核数*/
// System.out.println(Runtime.getRuntime().availableProcessors());
// System.out.println(5>>2);
//
Ticket ticket = new Ticket();
new Thread(()->{
for (int i = 0; i < 50; i++) {
ticket.sale();
}
}).start();
new Thread(()->{
for (int i = 0; i < 50; i++) {
ticket.sale();
}
}).start();
new Thread(()->{
for (int i = 0; i < 50; i++) {
ticket.sale();
}
}).start();
}
}
class Ticket{
private int ticket = 40;
public synchronized void sale(){
if (ticket>0){
System.out.println("卖出了"+ticket+"号票。剩余"+--ticket+"张票。");
}
}
}
/*使用lock锁的方式实现多线程安全*/
class Test02{
public static void main(String[] args) {
System.out.println("使用了非公平锁");
Ticket2 ticket = new Ticket2();
new Thread(()->{
for (int i = 0; i < 50; i++) {
ticket.sale();
}
}).start();
}
}
class Ticket2{
private int ticket = 40;
Lock lock = new ReentrantLock();
public void sale(){
try{
lock.lock();
if (ticket>0){
System.out.println("卖出了"+ticket+"号票。剩余"+--ticket+"张票..。");
}
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}