//1.定义一个Fruit水果类
// 成员变量:stock库存
// 构造方法、set和get
public class Fruit {
private int stock;
boolean flag=true;
public Fruit() {
}
public Fruit(Integer stock) {
this.stock = stock;
}
public Integer getStock() {
return stock;
}
public void setStock(Integer stock) {
this.stock = stock;
}
@Override
public String toString() {
return "Fruit{" +
"stock=" + stock +
'}';
}
}
//定义一个官网线程类:NetShop,实现Runnable接口
// 完成卖出水果的动作
public class NetShop implements Runnable {
private Fruit jg;
public NetShop(Fruit jg){
this.jg=jg;
}
@Override
public void run() {
while (true) {
synchronized (jg) {
if (jg.flag == true) {
try {
jg.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer stock = jg.getStock();
if (stock > 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
jg.setStock(--stock);
System.out.println(Thread.currentThread().getName() + "正在卖出第" + (100 - stock) + "份,还剩余" + stock + "份");
jg.flag = true;
}
jg.notify();
if (jg.getStock() <= 0) {
break;
}
}
}
}
}
//3.定义一个实体店线程类:FrontShop,实现Runnable接口
// 完成卖出水果的动作
public class FrontShop implements Runnable{
private Fruit jg;
public FrontShop(Fruit jg){
this.jg=jg;
}
@Override
public void run() {
while (true){
synchronized (jg){
if (jg.flag==false) {
try {
jg.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Integer stock = jg.getStock();
if(stock>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
jg.setStock(--stock);
System.out.println(Thread.currentThread().getName()+"正在卖出第"+(100-stock)+"份,还剩余"+stock+"份");
jg.flag=false;
}
jg.notify();
if (jg.getStock()<=0){
break;
}
}
}
}
}
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Text {
public static void main(String[] args) {
Fruit fruit = new Fruit(100);
NetShop netShop = new NetShop(fruit);
FrontShop frontShop = new FrontShop(fruit);
Thread thread = new Thread(netShop, "网店");
Thread thread1 = new Thread(frontShop, "实体");
ExecutorService service= Executors.newFixedThreadPool(2);
thread.start();
thread1.start();
service.shutdown();
}
} |
|