import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class lx4 {
public static Integer num[] = {0};
public static Map<String, Thread> map = new HashMap<>();
public static int s = 0;
public static int x = 0;
public static int h = 0;
public static void main(String[] args) {
Long startTime = Calendar.getInstance().getTime().getTime();
Thread thread1 = new Thread(new ShengChanZhe());
Thread thread2 = new Thread(new XiaoFeiZhe());
Thread thread21 = new Thread(new XiaoFeiZhe());
//Thread thread3 = new Thread(new ZhuangTai());
thread1.setName("生产者");
thread2.setName("消费者");
thread21.setName("黄牛");
thread2.setPriority(Thread.MIN_PRIORITY);
thread21.setPriority(Thread.MAX_PRIORITY);
map.put("s", thread1);
map.put("x", thread2);
map.put("x1", thread21);
thread1.start();
thread2.start();
thread21.start();
//thread3.start();
Long endTime = Calendar.getInstance().getTime().getTime();
System.out.println("一共耗时:"+(endTime-startTime));
}
}
class ShengChanZhe implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
/*try {
Thread.sleep(10);
}catch (InterruptedException e){
e.printStackTrace();
}*/
synchronized (lx4.num) {
try {
lx4.num.notifyAll();
while (lx4.num[0] >= 40) {
lx4.num.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
lx4.num[0]++;
lx4.s++;
//System.out.println(Thread.currentThread().getName()+"生产了一件商品,剩余:" + lx4.num[0]);
}
}
System.out.println("小米生产了"+lx4.s+"件商品");
System.out.println("黄牛消费了"+lx4.h+"件商品");
System.out.println("消费者消费了"+lx4.x+"件商品");
}
}
class XiaoFeiZhe implements Runnable {
@Override
public void run() {
while (true) {
synchronized (lx4.num) {
try {
lx4.num.notifyAll();
while (lx4.num[0] <= 0) {
lx4.num.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
lx4.num[0]--;
if(Thread.currentThread().getName().equals("黄牛")){
lx4.h++;
}else {
lx4.x++;
}
//System.out.println(Thread.currentThread().getName()+"消费了一件商品,剩余:" + lx4.num[0]);
}
}
}
}
class ZhuangTai implements Runnable{
@Override
public void run(){
try {
while (true){
Boolean b1 = lx4.map.get("s").isAlive();
Boolean b2 = lx4.map.get("x").isAlive();
if(b1==true){
System.out.println("生产者线程状态为:存活");
}else {
System.out.println("生产者线程状态为:失活");
}
if (b2==true){
System.out.println("消费者线程状态为:存活");
}else {
System.out.println("消费者线程状态为:失活");
}
Thread.sleep(10000);
synchronized (lx4.num){
lx4.num.notifyAll();
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
java 生产者消费者练习
最新推荐文章于 2021-10-14 16:59:34 发布