package IO;
/*
定义主方法,调用创建与使用两个方法来操作对象
例子为生产笔记本与买笔记本两个对象,被操作对象为笔记本。
考虑到存在购买者进行购买活动的时候存在生产者没有完成生产的情况,
多设计一个参数。当笔记本的状态为真的时候,生产线程等待,等待购买完成唤醒
**/
public class jkkkld {
public static void main(String[] args) {
Pc pc = new Pc();
Customer cu = new Customer(pc);
Product pr = new Product(pc);
Thread th1 = new Thread(cu);
Thread th2 = new Thread(pr);
th1.start();
th2.start();
}
}
//定义电脑类,有 牌子与使用定位两种属性
//添加用来判断的属性
class Pc{
String brand;
String method;
boolean statu = false;
}
//定义生产商类交替生产两个品牌的电脑
class Product implements Runnable{
private Pc pc = null;
//定义计数器来实现交替生产电脑
int count = 0;
public Product(Pc pc) {
super();
this.pc = pc;
}
@Override
public void run() {
while(true) {
//设置线程锁,防止两个线程同时出现访问状态的
//进行判断后选择是否进行生产活动
synchronized(pc) {
if(!pc.statu) {//状态为false,进行生产
if(count %2==0) {
pc.brand = “联想”;
pc.method = “办公”;
pc.statu = !pc.statu;
}else {
pc.brand = “神舟”;
pc.method = “玩游戏”;
pc.statu = !pc.statu;
}
count++;
//生产完毕唤醒线程
pc.notify();
}else {//状态为true,进行休眠
try {
pc.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
//定义客户来购买电脑,
class Customer implements Runnable{
//保证与厂商生产的为同一个对象的电脑
private Pc pc = null;
int count = 1;
public Customer(Pc pc) {
super();
this.pc = pc;
}
@Override
public void run() {
while(true) {
synchronized (pc) {
if(pc.statu) {//电脑的状态为true,可以进行购买
System.out.println(“购买了第”+count+“台电脑”);
System.out.println(“brand:”+pc.brand);
System.out.println(“method:”+pc.method);
count++;
pc.statu = !pc.statu;
//取出来产品,进行唤醒
pc.notify();
}else {
try {
pc.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}