线程安全产生的原理:
线程安全问题解决: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.locksLock
实现提供了比使用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