1 synchronized 锁定的是当前对象的成员变量,也就是说无论当前对象有几个synchronized代码块,他们使用的是同意个锁,一个对象只有一个锁
2 notifyAll 之后不会立马去唤醒而是等当前代码执行结束之后才回去唤醒
class Product{
private int productQty = 0;
public synchronized void increment() throws InterruptedException{
//为了防止出现虚假唤醒,请不要使用if,使用while才是正确的
//因为使用if 当线程被唤醒的时候不会再去检查条件是否成立
while(productQty != 0){
this.wait();
}
productQty++;
System.out.println(Thread.currentThread().getName()+"---"+"当前添加之后有几个---"+productQty);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException{
while(productQty == 0){
this.wait();
}
productQty--;
System.out.println(Thread.currentThread().getName()+"---"+"当前减少之后有几个---"+productQty);
this.notifyAll();
}
}
public class MyClass4 {
public static void main(String[] args) {
final Product product = new Product();
//以下只是4个线程 两个增加,两个减少
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
product.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"线程A").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
product.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"线程B").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
product.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"线程C").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0; i < 10; i++){
try {
product.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"线程D").start();
}
}
使用lock也是可以对上面的代码进行代替的
main 方法同上
class Product{
private int productQty = 0;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void increment() throws InterruptedException{
lock.lock(); //给该代码快上锁
try {
while(productQty != 0){
condition.await(); //this.wait(); 被前面的替换
}
productQty++;
System.out.println(Thread.currentThread().getName()+"---"+"当前添加之后有几个---"+productQty);
condition.signalAll(); //this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void decrement() throws InterruptedException{
lock.lock(); //给该代码快上锁
try {
while(productQty == 0){
condition.await(); //this.wait(); 被前面的替换
}
productQty--;
System.out.println(Thread.currentThread().getName()+"---"+"当前减少之后有几个---"+productQty);
condition.signalAll(); //this.notifyAll();
} catch (Exception e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}