【1】利用同步代码块解决问题
package com.msb.test10; import com.sun.media.sound.RIFFInvalidDataException; /** * @author : liu * 日期:16:02:52 * 描述:IntelliJ IDEA * 版本:1.0 */ public class CustomerThread extends Thread{//消费者线程 //共享商品资源 private Product p; public CustomerThread(Product p) { this.p = p; } @Override public void run() { synchronized (p){ for (int i = 1; i <= 10 ; i++) {//消费次数 System.out.println("消费者消费了:"+ p.getBrand()+"---"+ p.getName()); } } } }
package com.msb.test10; /** * @author : liu * 日期:15:45:09 * 描述:IntelliJ IDEA * 版本:1.0 */ public class ProducerThread extends Thread{//生产者线程 //共享商品 private Product p; public ProducerThread(Product p) { this.p = p; } @Override public void run() { synchronized(p){ for (int i = 1; i <= 10; i++) {//生产十个商品 if(i%2==0){ //生产费列罗巧克力 p.setBrand("费列罗"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } p.setName("巧克力"); }else{ p.setBrand("哈尔滨"); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } p.setName("啤酒"); } System.out.println("生产者生产了:"+p.getBrand() + "---"+ p.getName()); } } } }
【2】利用同步方法解决问题
package com.msb.test11; /** * @author : liu * 日期:15:42:06 * 描述:IntelliJ IDEA * 版本:1.0 */ public class Product {//商品类 //品牌 private String brand; //名字 private String name; //setter,getter方法: 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 synchronized void setProduct(String brand ,String name){ this.setBrand(brand); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } this.setName(name); System.out.println("生产者生产了:"+this.getBrand() + "---"+ this.getName()); } //消费商品 public synchronized void getProduct(){ System.out.println("消费者消费了:"+ this.getBrand()+"---"+ this.getName()); } }
package com.msb.test11; /** * @author : liu * 日期:15:45:09 * 描述:IntelliJ IDEA * 版本:1.0 */ public class ProducerThread extends Thread{//生产者线程 //共享商品 private Product p; public ProducerThread(Product p) { this.p = p; } @Override public void run() { for (int i = 1; i <= 10; i++) {//生产十个商品 if (i%2==0){ p.setProduct("费列罗","巧克力"); }else{ p.setProduct("哈尔滨","啤酒"); } } } }
package com.msb.test11; /** * @author : liu * 日期:16:02:52 * 描述:IntelliJ IDEA * 版本:1.0 */ public class CustomerThread extends Thread{//消费者线程 //共享商品资源 private Product p; public CustomerThread(Product p) { this.p = p; } @Override public void run() { synchronized (p){ for (int i = 1; i <= 10 ; i++) {//消费次数 p.getProduct(); } } } }
标签:Product,String,void,brand,通信,分解,线程,public,name From: https://www.cnblogs.com/jeldp/p/17001147.html