1.创建Lock锁对象的方式:使用实现类ReentrantLock创建Lock对象。
(1)Lock lock=new ReentrantLock();
注:相当于synchronized(this)。
(2)static Lock lock=new ReentrantLock();
注:相当于synchronized(类.class)。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class mysellticket implements Runnable{
public mysellticket(){
//测试出来在创建不同对象的时候打印出来的lock对象一样
System.out.println(lock);
}
private static int tickets=10;
private static Lock lock=new ReentrantLock();
private int x=5;
@Override
public void run() {
while (x>0) {
try {
lock.lock();
if (x < 0 || x == 0) {//不加这个判断x<=0,结果会多输出两条数据
break;
}
if (tickets > 0) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":正在销售第"+tickets+"张票");
tickets--;
}
}finally {
x--;
lock.unlock();
}
}
}
public static void main(String[] args) {
//同一个my对象,可以锁住。
// mysellticket my = new mysellticket();
// Thread t1 = new Thread(my, "窗口1");
// Thread t2 = new Thread(my, "窗口2");
// t1.start();
// t2.start();
//不同一个my,my1对象,不能锁住。
mysellticket my = new mysellticket();
mysellticket my1 = new mysellticket();
Thread t1 = new Thread(my, "窗口1");
Thread t2 = new Thread(my1, "窗口2");
t1.start();
t2.start();
//注:要是lock对象加上static修饰,则会锁住类
}
}