您的当前位置:首页正文

聪聪工作室---多线程--- LeanThreadCommuni

来源:花图问答

一个程序就是一个进程

多线程指在同一个程序中的多个应用和功能

LeanThreadCommunication.java 代码

package Boxtest;

public class LeanThreadCommunication {
    public static void main(String[] args) {
        Box box=new Box();
        Thread producer=new Producer(box);
        Consumer consumer=new Consumer(box);
        producer.start();
        consumer.start();
    }

}

LeanThreadCommunication.png

Box.java 代码

class Box{
    public int boxValue=0;
}

class Producer extends Thread{
    private Box box;
    public Producer(Box box){
        this.box=box;
    }
    @Override
    public void run() {
        for (int i = 1; i < 6; i++) {
            synchronized (box) {
                while(box.boxValue!=0){
                    try {
                        System.out.println("Producer: Box是满的:进入等待队列");
                        box.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                box.boxValue=i;
                System.out.println("Producer: Box中放入了"+i+",并通知其他等待者");

                box.notify();
                
            }
        }
    }
}
Box.png

Consumer.java 代码

class Consumer extends Thread{
    private Box box;
    public Consumer(Box box){
        this.box=box;
    }
    @Override
    public void run() {
        
        for (int i = 1; i < 6; i++) {
            synchronized (box) {
                while(box.boxValue==0){
                    try {
                        System.out.println("Consumer: Box是空的,进入等待队列");
                        box.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("Consumer: Box中取出了"+i+"并通知其他等待者");
                box.boxValue=0;
                box.notify();
            }
            
        }
        
    }
}
Consumer.png

聪聪工作室---Java---独家制作
版权所有,盗版必究!