/*
线程联合
需求: 模拟顾客去蛋糕店买蛋糕
蛋糕师傅现场制作
结论: 线程A在占有CPU资源期间联合B线程,那么线程A立刻中断执行
等到其联合的B线程执行完,A线程再重新排队等待,以便恢复执行
*/
class ThreadJoin implements Runnable
{
Cake cake;
Thread joinThread;
public void setJoinThread(Thread t)
{
joinThread=t;
}
public void run()
{
if(Thread.currentThread().getName().equals("顾客"))
{
System.out.println(Thread.currentThread().getName()+"等待"+joinThread.getName()+"制作蛋糕");
try
{
joinThread.start();
joinThread.join();
}
catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"买了"+cake.name+"---价格"+cake.price);
}
else if(Thread.currentThread()==joinThread)
{
System.out.println(joinThread.getName()+"开始制作蛋糕,请等待-----");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
cake=new Cake("生日蛋糕",125);
System.out.println(joinThread.getName()+"制作完成");
}
}
class Cake
{
int price;
String name;
Cake(String name,int price)
{
this.name=name;
this.price=price;
}
}
}
class SaleCakeDemo
{
public static void main(String[] args)
{
ThreadJoin a=new ThreadJoin();
Thread customer=new Thread(a);
Thread cakeMaker=new Thread(a);
customer.setName("顾客");
cakeMaker.setName("蛋糕师");
a.setJoinThread(cakeMaker);
customer.start();
}
}
|
|