熟悉java多线程中休眠,synchronized,Thread.sleep(long)的用法
- package cn.javase.mxy;
- class Product {
- private String kind;
- private String name;
- private String price;
- private boolean flag = true;
- public synchronized void set(String kind, String name, String price){
- if(this.flag == false){
- try {
- super.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- this.kind = kind;
- this.name = name;
- this.price = price;
- this.flag = false;
- super.notify();
- }
-
- public synchronized void get(){
- if(this.flag == true){
- try {
- super.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.out.println("产品类型:"+kind+",产品名称:"+name+",产品价格:"+price);
- this.flag = true;
- super.notify();
- }
- }
- class Productor implements Runnable{
- private Product product;
- public Productor(Product product){
- this.product = product;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int x = 0; x < 100; x++){
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- if(x % 2 == 0){
- this.product.set("药品", "云南白药酊", "30元");
- }else{
- this.product.set("生活用品", "云南白药牙膏", "20元");
- }
- }
- }
- }
- class Consumer implements Runnable{
- private Product product;
- public Consumer (Product product){
- this.product = product;
- }
- @Override
- public void run() {
- // TODO Auto-generated method stub
- for(int x = 0; x < 100; x++){
- this.product.get();
- }
- }
- }
复制代码
- package cn.javase.mxy;
- public class Test {
- public static void main(String[] args) {
- Product p = new Product();
- new Thread(new Productor(p)).start();
- new Thread(new Consumer(p)).start();
- }
- }
复制代码 |