1、类
package com.wyq.syn;
public class Product {
private String brand;
private String name;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product(String brand, String name) {
super();
this.brand = brand;
this.name = name;
}
public Product() {
super();
}
}
2、生产者
package com.wyq.syn;
public class Producer implements Runnable{
private Product pro;
public Producer(Product pro) {
super();
this.pro = pro;
}
@Override
public void run() {
for(int i = 0;i<10;i++){
if(i%2==0){
pro.setBrand("旺仔");
pro.setName("小馒头");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"生产了————————————>"+pro.getBrand()+"牌子的"+pro.getName());
}else{
pro.setBrand("娃哈哈");
pro.setName("矿泉水");
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"生产了————————————>"+pro.getBrand()+"牌子的"+pro.getName());
}
}
}
}
3、消费者
package com.wyq.syn;
public class Consumer implements Runnable{
private Product pro;
public Product getPro() {
return pro;
}
public void setPro(Product pro) {
this.pro = pro;
}
public Consumer(Product pro) {
super();
this.pro = pro;
}
@Override
public void run() {
for(int i =0;i<10;i++){
System.out.println(Thread.currentThread().getName()+"消费了第"+i+"个"+pro.getBrand()+"品牌的"+pro.getName());
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
4、测试类
package com.wyq.syn;
public class Test1 {
public static void main(String[] args) {
Product pro = new Product();
Producer p = new Producer(pro);
Thread t = new Thread(p,"生产者");
Consumer c = new Consumer(pro);
Thread t2 = new Thread(c, "消费者");
t.start();
t2.start();
}
}