类1
public class Cangku {
public static int num = 50;
private String name;
Cangku(String name){
this.name = name;
}
public synchronized void cai(){
while (num == 100){
try {
this.wait();
notify();
}
catch (InterruptedException e){
e.getStackTrace();
}
}
for(int i = 1;i<=(100-num);i++){
System.out.println("正在采集一个苹果");
num++;
System.out.println("目前仓库拥有苹果"+ num +"个");
}
}
public synchronized void mai(){
while (num==0){
try {
this.wait();
this.notify();
}
catch (InterruptedException e){
e.getMessage();
}
}
for(int i = 1;i<=num;i++){
System.out.println("正在销售一个苹果");
num--;
System.out.println("目前仓库拥有苹果"+ num +"个");
}
}
}
类2
public class Test5 implements Runnable{
private Cangku cangku;
Test5(Cangku cangku){
this.cangku = cangku;
}
@Override
public void run() {
cangku.cai();
}
}
类3
public class Test6 implements Runnable {
private Cangku cangku;
Test6(Cangku cangku){
this.cangku = cangku;
}
@Override
public void run() {
cangku.mai();
}
}
类4
public class Test7 {
public static void main(String args[]){
Cangku cangku = new Cangku("苹果仓库");
Thread thread = new Thread(new Test5(cangku),"采集线程");
thread.start();
Thread thread1 = new Thread(new Test6(cangku),"销售线程");
thread1.start();
}
}
本文介绍了一个使用Java实现的仓库管理案例,通过两个线程分别模拟苹果的采集与销售过程,并利用synchronized关键字来确保线程安全。初始时仓库中有50个苹果,采集线程会在仓库苹果数量少于100时进行采集操作,而销售线程则在有苹果的情况下进行销售。
589

被折叠的 条评论
为什么被折叠?



