package com.Test.Demo.ThreadTest;
public class ThreadTest01 {
public static void main(String[] args){
AoLiGei aoLiGei = new AoLiGei();
Runnable thread1 = new Thread01( aoLiGei );
Runnable thread2 = new Thread02( aoLiGei );
Thread thread01= new Thread(thread1,"消费者");
Thread thread02= new Thread(thread2,"生产者");
thread01.start();
thread02.start();
}
}
class Thread01 implements Runnable{
private AoLiGei aoLiGei;
public Thread01(AoLiGei aoLiGei){
this.aoLiGei=aoLiGei;
}
@Override
public void run() {
while(true){
synchronized (this.aoLiGei){
if(this.aoLiGei.getCount()==0){
this.aoLiGei.notifyAll();
try {
this.aoLiGei.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
this.aoLiGei.xiaoFei();
System.out.println(Thread.currentThread().getName()+"线程执行 消费者消费 奥利给剩余:"+this.aoLiGei.getCount()+"坨");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class Thread02 implements Runnable{
private AoLiGei aoLiGei;
public Thread02(AoLiGei aoLiGei){
this.aoLiGei=aoLiGei;
}
@Override
public void run() {
while(true){
synchronized (this.aoLiGei){
if(this.aoLiGei.getCount()==10){
this.aoLiGei.notifyAll();
try {
this.aoLiGei.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
this.aoLiGei.shengChan();
System.out.println(Thread.currentThread().getName()+"线程执行 生产者生产 奥利给剩余:"+this.aoLiGei.getCount()+"坨");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class AoLiGei{
private int count=0;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void xiaoFei(){
this.count--;
}
public void shengChan(){
this.count++;
}
}