package thread;
import java.util.concurrent.locks.*;
/**
* @author Alina
* @date 2021年12月20日 11:07 下午
* JDK5新特性
* import java.util.concurrent.locks 包
* lock接口
* void lock() 获取锁,进同步
* void unlock () 释放锁,出同步
*
*
*/
class Tickerts implements Runnable{
private Lock l = new ReentrantLock();
private int ticketnum = 100;
public void run(){
while(true){
try{
l.lock();
if(ticketnum>0){
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"..."+"出售的票数为:"+ticketnum);
ticketnum--;
}
}catch (Exception e ){}
finally {
l.unlock();
}
}
}
}
public class LockDemo {
public static void main(String[] args) {
Tickerts ti = new Tickerts();
Thread t0 = new Thread(ti);
Thread t1 = new Thread(ti);
Thread t2 = new Thread(ti);
t0.start();
t1.start();
t2.start();
}
}
package thread;
/**
* @author Alina
* @date 2021年12月20日 11:55 下午
*/
class A_lock{
public static A_lock A_lock = new A_lock();
}
class B_lock{
public static B_lock B_lock = new B_lock();
}
class DeadLock implements Runnable {
private boolean love ;
public DeadLock(boolean love) {
this.love = love;
}
public void run(){
while (true){
if(love){
synchronized (A_lock.A_lock){
System.out.println("A");
synchronized (B_lock.B_lock){
System.out.println("B");
}
}
}else {
synchronized (B_lock.B_lock){
System.out.println("B");
synchronized (A_lock.A_lock){
System.out.println("A");
}
}
}
}
}
}
public class DeadDome {
public static void main(String[] args) {
DeadLock d0 = new DeadLock(true);
DeadLock d1 = new DeadLock(false);
Thread t0 = new Thread(d0);
Thread t1 = new Thread(d1);
t0.start();
t1.start();
}
}