📄 thread13.java
字号:
class ham //把装汉堡包的盒子作为监视器类
{
static Object box=new Object();
static int totalmaterial=10;
static int sales=0;
static int production=5;
}
class hmaker extends Thread //厨师线程类
{
public void make()
{
synchronized(ham.box)
{
(ham.production)++;
try
{
ham.box.notify();
}
catch(Exception e){}
}
}
public void run()
{
while(ham.production<ham.totalmaterial)
{
if(ham.production>0)
{
System.out.println("厨师"+getName()+":"+"汉堡来了(总共"+(ham.production-ham.sales)+"个)");
}
try
{
sleep(3000);
}
catch(Exception e){}
make();
}
}
}
class hassistant extends Thread
{
public void sell()
{
if(ham.production==0)
{
System.out.println("营业员:顾客朋友们,请稍微等一下,汉堡没了!!");
}
try
{
ham.box.wait();
}
catch(Exception e){}
ham.sales++;
System.out.println("营业员:顾客好,汉堡上来了,(总共卖了"+ham.sales+"个)");
}
public void run()
{
while(ham.sales<ham.production)
{
try
{
sleep(1000);
}
catch(Exception e){}
sell();
}
}
}
public class thread13
{
public static void main(String[] args)
{
hmaker maker=new hmaker();
hassistant assistant=new hassistant();
maker.setName("甲");
maker.start();
assistant.start();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -