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();
}
}
}
java线程学习第一天__低配版的卖面包机
Posted laiso
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java线程学习第一天__低配版的卖面包机相关的知识,希望对你有一定的参考价值。
以上是关于java线程学习第一天__低配版的卖面包机的主要内容,如果未能解决你的问题,请参考以下文章
Java利用Java的注解和反射实现一个"低配版"的依赖注入