1、商品类
package com.wyq.syn;
public class Product2 {
private String name;
private String brand;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public Product2(String name, String brand) {
super();
this.name = name;
this.brand = brand;
}
public Product2() {
super();
}
//编写同步线程的方法,用于生产商品
public synchronized void produ(String name, String brand){
this.setName(name);
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
this.setBrand(brand);
System.out.println(Thread.currentThread().getName()+"正在生产第"+"个"+this.brand+"牌子的"+this.name);
}
//编写同步线程的方法,用于消费商品
public synchronized void con(){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"正在消费"+this.brand+"————————>牌子的"+this.name);
}
}
2、生产者类
package com.wyq.syn;
public class Producer2 implements Runnable{
private Product2 pro;
public Product2 getPro() {
return pro;
}
public void setPro(Product2 pro) {
this.pro = pro;
}
public Producer2(Product2 pro) {
super();
this.pro = pro;
}
@Override
public void run() {
for(int i = 0;i<10;i++){
if(i%2==0){
pro.produ("小馒头", "旺仔");
}else{
pro.produ("矿泉水", "娃哈哈");
}
}
// for(int i = 0;i<10;i++){
// synchronized (pro) {
// if(i%2==0){
// pro.setBrand("旺仔");
// try {
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// pro.setName("小馒头");
// }else{
// pro.setBrand("娃哈哈");
// try {
// Thread.sleep(200);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// pro.setName("矿泉水");
// }
// System.out.println(Thread.currentThread().getName()+"生产了"+"第"+i+"个"+pro.getBrand()+"牌子的"+pro.getName());
// }
// }
}
}
3、消费者类
package com.wyq.syn;
public class Consumer2 implements Runnable{
private Product2 pro;
public Product2 getPro() {
return pro;
}
public void setPro(Product2 pro) {
this.pro = pro;
}
public Consumer2(Product2 pro) {
super();
this.pro = pro;
}
@Override
public void run() {
for(int i =0;i<10;i++){
pro.con();
}
// for(int i=0;i<10;i++){
// System.out.println(Thread.currentThread().getName()+"正在消费第"+i+"个——————>"+pro.getBrand()+"牌子的"+pro.getName());
// }
}
}
4、测试类
package com.wyq.syn;
public class Test2 {
public static void main(String[] args) {
Product2 pro = new Product2();
Producer2 p = new Producer2(pro);
Consumer2 c = new Consumer2(pro);
Thread t1 = new Thread(p, "生产者");
Thread t2 = new Thread(c, "消费者");
t1.start();
t2.start();
}
}