实现一个生产者,消费者
思路:用lock锁。定义一个类成员变量 max_value,min_value代表资源的最大,最小数量。
java
package org.app.common;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Resource {
private int MAX_VALUE= 3;
private int MIN_VALUE=0;
private int number = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void consume(){
try {
lock.lock();
while(number <= MIN_VALUE){
condition.await();
}
number--;
System.out.println("【消费者】:消费了一个产品,【现仓储量为】:" + number);
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void produce(){
try {
lock.lock();
while (number >MAX_VALUE) {
condition.await();
}
number++;
System.out.println("【生产者】:生产了一个产品\t【现仓储量为】:" + number);
condition.signalAll();
}catch (Exception e){
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
Resource resouce = new Resource();
new Thread(()->{
for(int i=0;i<10;i++){
resouce.produce();
}
}).start();//生产者
//消费者
new Thread(()->{
for (int i=1;i<=5;i++){
resouce.consume();
}
},String.valueOf("消费者")).start();
}
}
线程交替打印问题
2个线程交替打印1-10
问题解决方法比较多。
java
private static volatile int num = 1;
private static Object lock = new Object();
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
while (num < 99) {
if (num % 2 == 0) {
synchronized (lock) {
lock.notify();
System.out.println("t1" + "_" + num);
num++;
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
};
Thread t2 = new Thread() {
public void run() {
while (num < 99) {
if (num % 2 == 1) {
synchronized (lock) {
lock.notify();
System.out.println("t2" + "_" + num);
num++;
try {
lock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
};
t1.start();
t2.start();
java
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Main2 {
private int time;
private int state;
private Lock lock = new ReentrantLock();
public Main2(int time){
this.time = time;
}
public void print(String name,int targetNum){
for(int i=0;i<time;){
lock.lock();
if (state % 3 == targetNum) {
state++;
i++;
System.out.println(name);
}
lock.unlock();
}
}
public static void main(String[] args) {
Main2 main2 = new Main2(2);
new Thread(()->{
main2.print("B", 1);
},"B").start(); new Thread(()->{
main2.print("C", 2);
},"C").start();
new Thread(()->{
main2.print("A", 0);
},"A").start();
}
}