首页 > 编程语言 > 详细

线程安全问题

时间:2020-05-19 20:58:59      阅读:57      评论:0      收藏:0      [点我收藏+]

线程安全产生的原理:

技术分享图片

 

 

 

线程安全问题解决:1、同步代码块 :synchronized

         2、同步方法:

          
private int key = 100;

@Override
public void run() {
while (true){
methon();
}
}
public synchronized void methon(){
synchronized (this){
if (key > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖" + key + "张票");
key--;
}else {
return;
}
}
}

3.静态方法:借口实现类名.class作为锁对象
private static int key = 100;

@Override
public void run() {
while (true){
methon();
}
}
public static /*synchronized*/ void methon(){
synchronized (ThreadDemo.class){//ThreadDemo.class作为锁对象
if (key > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在卖" + key + "张票");
key--;
}else {
return;
}
}
}

4.使用lock:java.util.concurrent.locks Lock 实现提供了比使用 synchronized 方法和语句可获得的更广泛的锁定操作
其中有两个方法:void lock() 获取锁。
        void unlock() 释放锁。
1)在成员变量中定义java.util.concurrent.locks.ReentrantLock implements lock
可以使用多态定义:lock l = new ReentrantLock();
2)在可能会出现安全问题之前使用lock
3)在可能会出现安全问题之后使用unlock
private static int key = 100;
Lock l = new ReentrantLock();//多态

@Override
public void run() {
while (true){
l.lock();
if (key > 0) {
try {
Thread.sleep(10);
System.out.println(Thread.currentThread().getName() + "正在卖" + key + "张票");
key--;
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
l.unlock();
}
}
}
}



 

线程安全问题

原文:https://www.cnblogs.com/anyuwu/p/12919189.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!