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ufH+/98PLhJSitwlglgw7hn4flI784T8TgTlOzTTQKGIDBhOScY4Vm9+fQqc1ZBsyiTQAAOGWfGZd/f3UBw8Nn/Dgffg02fPblv8jDvDj8jqM+lJrD71y3/vYsndgWluDcixYCnZtq8R+QCaTIZGJmwkJYZzAmazTC9WSv4+JJ47plbmmPkKQBlwGDYHnhiClw251/8Riaw+32OzpmAdhGMMJuWhktE9TLEQaCs4APec2XS5INSJQSa6SGr6eyJ58L5Td0ZPbMxNS/GZYW3PIHpB6lb7rJ6qwlsbQLxJwRb66/6qQlscwJ1c7a5L9XV1idQN2frO1T9bXMCdXO2uS/V1dYnUDdn6ztU/W1zAnVztrkv1dXWJ1A3Z+s7VP1tcwJ1c7a5L9XV1idQN2frO1T9bXMCdXO2uS/V1dYnUDdn6ztU/W1zAnVztrkv1dXWJ1A3Z+s7VP1tcwJ1c7a5L9XV1ifwP0BbfAWyLtnJAAAAAElFTkSuQmCC" alt="" />
代码:
package com.niit.syntronized; /**
* @author: Annie
* @date:2016年6月15日
* @description:线程联合(顾客到蛋糕店买蛋糕)使用join()方法
*/
public class ThreadJoin implements Runnable{ Thread joinThread;
Cake cake;
public void setThread(Thread t){
joinThread =t;
}
@Override
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.price); }else if (Thread.currentThread()==joinThread){
System.out.println(Thread.currentThread().getName()+"开始制作蛋糕,请耐心等待.........");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cake = new Cake("生日蛋糕",158);
System.out.println(joinThread.getName()+"制作完毕");
} } class Cake {
int price;
String name; public Cake(String name,int price) {
this.price = price;
this.name = name;
} } public static void main(String[] args) {
ThreadJoin threadJoin = new ThreadJoin();
Thread customer = new Thread(threadJoin);
customer.setName("顾客");
Thread cakeMake = new Thread(threadJoin);
cakeMake.setName("蛋糕");
threadJoin.setThread(cakeMake);
customer.start();
}
}