什么是线程安全问题呢?
举个例子:
假设A和B和C都想要去厕所,但是只有一个厕所,A进去了,门没锁,然后B发现他也能进去,然后B就进去了,就出了事故,要解决这个问题,就要给门加上一把锁,使得A进去之后,在A出来之前,B、C只能在外边等着。
案例:不安全的售票:
public class Demo001 extends Thread{
private int ticket=100;
@Override
public void run() {
while (true){
if (ticket==0){
System.out.println(“票售光,请明天再来”);
break;
}
if (ticket>0){
System.out.println(Thread.currentThread().getName()+“正在售票”+“票号为”+ticket);
ticket–;
}
}
}
public static void main(String[] args) {
Demo001 demo001 = new Demo001();
Thread thread1= new Thread(demo001);
Thread thread2 = new Thread(demo001);
Thread thread3 = new Thread(demo001);
thread1.setName("窗口一");
thread2.setName("窗口二");
thread3.setName("窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}
用下图描述上述问题
在线程一判断有票进去抢票的同时,线程二与线程三完成了相同的操作,然而当其中一个抢到100号票的时候并且出去的时候,并没有把这个信息提供给线程二与线程三,就会出现123都抢到100号票的现象。
简要概括为对共享资源的同时获取出错,要将其指定顺序,就是一进去拿资源的时候二与三需要在外边等着,直到一取完资源,二/三才会有一个进去继续这样的循环
为了解决这个线程的安全问题,提供以下方法;
1.synchronized (同步代码块/同步方法)
2.lock(lock()锁为jdk5.0之后的新的特性,在jdk5.0之前无法使用)
1.synchronized(同步代码块)
值得注意的是在使用锁的时候需要给不同线程的同一共享资源同一把锁,不然就会出现,A的锁只对A有效,bc同理。
public class Demo001 extends Thread{
private int ticket=100;
@Override
public void run() {
while (true){
synchronized (Demo001.class){//同步代码块
if (ticket==0){
System.out.println("票售光,请明天再来");
break;
}
if (ticket>0){
System.out.println(Thread.currentThread().getName()+"正在售票"+"票号为"+ticket);
ticket--;
}
}
}
}
public static void main(String[] args) {
Demo001 demo001 = new Demo001();
Thread thread1= new Thread(demo001);
Thread thread2 = new Thread(demo001);
Thread thread3 = new Thread(demo001);
thread1.setName("窗口一");
thread2.setName("窗口二");
thread3.setName("窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}
由于类只会加载一次,所以类作为锁是唯一的,解决了使用对象做锁不唯一的可能。
2.synchronized(同步方法)
实例化一个ReentrantLock,使用ReentrantLock进行手动锁。
import java.util.concurrent.locks.ReentrantLock;
public class Demo001 extends Thread{
private int ticket=100;
private ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while (true){
try{
lock.lock();//锁
if (ticket==0){
System.out.println(“票售光,请明天再来”);
break;
}
if (ticket>0){
System.out.println(Thread.currentThread().getName()+“正在售票”+“票号为”+ticket);
ticket–;
}
}finally {
lock.unlock();//释放
}
}
}
public static void main(String[] args) {
Demo001 demo001 = new Demo001();
Thread thread1= new Thread(demo001);
Thread thread2 = new Thread(demo001);
Thread thread3 = new Thread(demo001);
thread1.setName("窗口一");
thread2.setName("窗口二");
thread3.setName("窗口三");
thread1.start();
thread2.start();
thread3.start();
}
}
总结
1.synchronized
2.lock
二者区别:
作为jdk5.0之后新特性的lock更像是人为手动解锁,更加的灵活。
lock可提供公平性 private ReentrantLock lock=new ReentrantLock(true);
lock大量同步线程
lock需要unlock不然会出现死锁现象