java多线程测试代码

package com.Test.Demo.ThreadTest;



// 程序功能: 实现消费者生产者模式 生产者最多生产10坨奥利给 消费者消费奥利给时奥利给数量必须大于0
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++;
    }
}
原文地址:https://www.cnblogs.com/fxzemmm/p/14847951.html