生產者和消費者之一對一
生產者和消費者之一對多
一對一
Clerk 庫存 最大隻能保存20件
Productor 生產者
Consumer 消費者
package com.zjx.thread;
public class TesCommunication1 {
public static void main(String[] args) {
Clerk c = new Clerk();
Productor p = new Productor(c);
p.start();
Consumer con= new Consumer(c);
con.start();
}
}
class Consumer extends Thread{
private Clerk c;
public Consumer(Clerk c) {
this.c = c;
}
@Override
public void run() {
while(true){
c.get();
}
}
}
class Productor extends Thread{
private Clerk c;
public Productor(Clerk c) {
this.c = c;
}
@Override
public void run() {
while(true){
c.save();
}
}
}
class Clerk{
int count = 0;
public synchronized void save(){
if (count >= 20) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("生產者生產了一件產品,目前庫存爲: "+(++count));
this.notify();
}
public synchronized void get(){
if (count <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消費者消費了一件產品,目前庫存爲: "+(--count));
this.notify();
}
}
多對多
notify -> notifyAll
if -> while
package com.zjx.thread;
public class TesCommunication2 {
public static void main(String[] args) {
Clerk2 c = new Clerk2();
Productor2 p1 = new Productor2("生產者路人甲號",c);
p1.start();
Productor2 p2 = new Productor2("生產者路人乙號",c);
p2.start();
Consumer2 con1= new Consumer2("*******消費者范冰冰",c);
con1.start();
Consumer2 con2= new Consumer2("*******消費者歐陽娜娜",c);
con2.start();
Consumer2 con3= new Consumer2("*******消費者迪麗熱巴",c);
con3.start();
}
}
class Consumer2 extends Thread{
private Clerk2 c;
public Consumer2(String name,Clerk2 c) {
super(name);
this.c = c;
}
@Override
public void run() {
while(true){
c.get();
}
}
}
class Productor2 extends Thread{
private Clerk2 c;
public Productor2(String name,Clerk2 c) {
super(name);
this.c = c;
}
@Override
public void run() {
while(true){
c.save();
}
}
}
class Clerk2{
int count = 0;
public synchronized void save(){
while(count >= 20) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"生產了一件產品,目前庫存爲: "+(++count));
this.notifyAll();
}
public synchronized void get(){
while (count <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"消費了一件產品,目前庫存爲: "+(--count));
this.notifyAll();
}
}