线程-临界资源问题
同步代码块方法
用同步代码块解决临界资源问题
/**
* 同步代码块
* @param args
*/
public static void main( String[] args ){
//实例化四个售票窗口
Runnable world = new Runnable() {
@Override
public void run() {
while (TicketCenter.restCount > 0){
/**
* synchronized ("") -->> 括号里面传入一个常量的,可以是字符串、int、对象、类等,就是不能是一个变量
* 比如一个常量++,或者new object()对象,这样所就会发生改变了,
* 也就是锁必须要每一个线程看到的锁是一样的
*/
synchronized ("A"){
if (TicketCenter.restCount<=0){
return;
}
System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余:"+ --TicketCenter.restCount +"张票");
}
}
}
};
//四个线程售票
Thread t1 = new Thread(world,"world - 1");
Thread t2 = new Thread(world,"world - 2");
Thread t3 = new Thread(world,"world - 3");
Thread t4 = new Thread(world,"world - 4");
//开启线程
t1.start();
t2.start();
t3.start();
t4.start();
}
public class TicketCenter {
static int restCount = 100;
}
每一个线程在执行遇到synchronized (“A”) 要是没有拿到锁A的话就会进入锁池里面,争取cpu资源和锁,
然后执行。
同步方法
/**
* 同步方法
* @param args
*/
public static void main( String[] args ){
//实例化四个售票窗口
Runnable world = new Runnable() {
@Override
public void run() {
while (TicketCenter.restCount > 0){
soldTicket();
}
}
};
//四个线程售票
Thread t1 = new Thread(world,"world - 1");
Thread t2 = new Thread(world,"world - 2");
Thread t3 = new Thread(world,"world - 3");
Thread t4 = new Thread(world,"world - 4");
//开启线程
t1.start();
t2.start();
t3.start();
t4.start();
}
public synchronized static void soldTicket(){
if (TicketCenter.restCount<=0){
return;
}
System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余:"+ --TicketCenter.restCount +"张票");
}
在同步方法里面,方法是一个静态方法,则锁是当前类的class,方法是一个非静态方法里面,锁则是this
ReentrantLock锁
ReentrantLock是一个锁对象,可以实例化,
ReentrantLock.lock() 方法上锁,
ReentrantLock.unlock()释放锁。
/**
* 使用ReentrantLock 上锁与解锁
* @param args
*/
public static void main( String[] args ){
//实例化锁对象
final ReentrantLock lock = new ReentrantLock();
//实例化四个售票窗口
Runnable world = new Runnable() {
@Override
public void run() {
while (TicketCenter.restCount > 0){
lock.lock();
if (TicketCenter.restCount<=0){
return;
}
System.out.println(Thread.currentThread().getName()+"卖出一张票,剩余:"+ --TicketCenter.restCount +"张票");
lock.unlock();
}
}
};
//四个线程售票
Thread t1 = new Thread(world,"world - 1");
Thread t2 = new Thread(world,"world - 2");
Thread t3 = new Thread(world,"world - 3");
Thread t4 = new Thread(world,"world - 4");
//开启线程
t1.start();
t2.start();
t3.start();
t4.start();
}