public class Saletext {
public static void main(String[] args) {
protector p=new protector();
counter c=new counter();
Thread t1=new Thread(p);
Thread t2=new Thread(c);
t1.setName("厂商");
t2.setName("消费者");
t1.start();
t2.start();
}
}
class phone{
Object object=new Object();
int phones=0;
}
class protector extends phone implements Runnable{
@Override
public void run() {
System.out.println("生产");
while (true) {
synchronized (object) {
if (phones < 20) {
phones++;
System.out.println(Thread.currentThread().getName() + "生产第" + phones + "部手机");
object.notify();
} else {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
class counter extends phone implements Runnable{
@Override
public void run() {
System.out.println("消费");
while (true) {
synchronized (object) {
if (phones >0) {
System.out.println(Thread.currentThread().getName() + "消费第" + phones + "部手机");
phones--;
object.notify();
} else {
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}