package Thread;
import javax.xml.bind.ValidationEvent;
class snacks{
private int SaledSnacks=0;
private int TotalSnacksNum=10; //初始化小吃店开始有10个面包
private int TOTALtimeOFSALE=0;
public synchronized boolean salesnacks() {
if (TotalSnacksNum>0) {
SaledSnacks++;
TotalSnacksNum--;
TOTALtimeOFSALE++;
System.out.println(Thread.currentThread().getName()+"卖出一个面包");
return true;
}else {
System.out.println("目前已经卖完了,需要等会儿才有");
return false;
}
}
public synchronized boolean makesnacks() {
TotalSnacksNum++;
TOTALtimeOFSALE+=3;
System.out.println(Thread.currentThread().getName()+"做出一个面包");
return true;
}
}
class SaleSnacks extends Thread{
private snacks Snacks=new snacks();
public SaleSnacks(String name,snacks s) {
super(name);
Snacks=s;
}
public void Validation() {
while(Snacks.salesnacks()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
if (!Snacks.salesnacks()) {
try {
Thread.sleep(5000);
while(Snacks.salesnacks()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
Validation();
}
@Override
public void run() {
Validation();
}
}
class MakeSnacks extends Thread{
private snacks Snacks=new snacks();
public MakeSnacks(String name,snacks s) {
super(name);
Snacks=s;
}
@Override
public void run() {
while(Snacks.makesnacks()) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
}
}
}
public class Thread_synchronized {
public static void main(String[] args) throws InterruptedException {
System.out.println("开始卖 snack!!!");
snacks AIMSnackShop=new snacks();
SaleSnacks sale1=new SaleSnacks("windows:A", AIMSnackShop);
SaleSnacks sale2=new SaleSnacks("windows:B", AIMSnackShop);
SaleSnacks sale3=new SaleSnacks("windows:C", AIMSnackShop);
MakeSnacks makeSnacks =new MakeSnacks("Make: A", AIMSnackShop);
sale1.start();
sale2.start();
sale3.start();
makeSnacks.start();
try {
Thread.sleep(500000);
} catch (IllegalThreadStateException e) {
e.printStackTrace();
}
}
}