public class test{
static int tickets = 15;
class SellTickets implements Runnable{
@Override
public void run(){
while (tickets > 0){
//同步代码块
synchronized(this){
if(tickets <= 0){
return;
}
}
}
}
}
}
public class ThreadSynchroniazedMethodSecurity{
static int tickets = 15;
class SellTickets implements Runnable{
@Override
public void run(){
while(tickets > 0){
synMethod();
}
}
synchronized void synMethod(){
synchronized(this){
....
}
}
}
}
Lock锁机制,通过创建Lock对象,采用lock()枷锁,unlock()解锁,来保护指定的代码块
public class ThreadLockSecurity{
static int tickets = 15;
class SellTickets implements Runnable{
Lock lock = new ReentrantLock();
@Override
public void run(){
while(tickets > 0){
try{
lock lock();
...
}catch(Exception e){
}finally{
lock.unlock();
...
}
}
}
}
}