Java实现线程安全的三种方式
1.同步代码块
代码语言:javascript复制public class test{
static int tickets = 15;
class SellTickets implements Runnable{
@Override
public void run(){
while (tickets > 0){
//同步代码块
synchronized(this){
if(tickets <= 0){
return;
}
}
}
}
}
}
2.同步方法
代码语言:javascript复制public class ThreadSynchroniazedMethodSecurity{
static int tickets = 15;
class SellTickets implements Runnable{
@Override
public void run(){
while(tickets > 0){
synMethod();
}
}
synchronized void synMethod(){
synchronized(this){
....
}
}
}
}
3.Lock锁机制
Lock锁机制,通过创建Lock对象,采用lock()枷锁,unlock()解锁,来保护指定的代码块
代码语言:javascript复制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();
...
}
}
}
}
}