生产者与消费者案例
案例:现在两个线程,可以操作初始值为零的一个变量,实现一个线程对该变量加1,一个线程对该变量减1,交替,来10轮,变量初始值为零。
1. synchronized 实现
package com.zym.test;
class ShareDate{
private int number = 0;
public synchronized void increment() throws InterruptedException {
//1判断
while(number != 0) {
this.wait();
}
//2干活
++number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3通知
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException {
//1判断
while(number == 0) {
this.wait();
}
//2干活
--number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3通知
this.notifyAll();
}
}
/**
* 现在两个线程,
* 可以操作初始值为零的一个变量,
* 实现一个线程对该变量加1,一个线程对该变量减1,
* 交替,来10轮,变量初始值为零
* @author machenike
*
*/
public class NotifyWaitDemo {
public static void main(String[] args) {
ShareDate sd = new ShareDate();
new Thread(() -> {
for(int i = 1 ; i<=10 ; i++) {
try {
sd.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(() -> {
for(int i = 1 ; i<=10 ; i++) {
try {
sd.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
运行结果:
2. lock实现
package com.zym.test1;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareDate{
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void increment() throws InterruptedException {
lock.lock();
try
{
//1判断
while(number != 0)
{
condition.await();
}
//2 干活
++number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException {
lock.lock();
try
{
//1判断
while(number == 0)
{
condition.await();
}
//2 干活
--number;
System.out.println(Thread.currentThread().getName()+"\t"+number);
//3 通知
condition.signalAll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* 现在两个线程,
* 可以操作初始值为零的一个变量,
* 实现一个线程对该变量加1,一个线程对该变量减1,
* 交替,来10轮,变量初始值为零
* @author machenike
*
*/
public class NotifyWaitDemo {
public static void main(String[] args) {
ShareDate sd = new ShareDate();
new Thread(() -> {
for(int i = 1 ; i<=10 ; i++) {
try {
sd.increment();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(() -> {
for(int i = 1 ; i<=10 ; i++) {
try {
sd.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
}
}
运行结果: