67.Java-資源搶奪案例(使用synchronized)

weixin_33806914發表於2018-06-11
  • 呼叫類
package com.test.thread;

public class Home {

    public static void main(String[] args) {
        
        ShareRegion share = new ShareRegion();
        
        new Thread(new Producer(share)).start();
        new Thread(new Consumer(share)).start();
        
    }
    
}
  • 資源共享類
package com.test.thread;

public class ShareRegion {
    
    private String name;
    private String sex;
    
    boolean isProduce = true;
    
    synchronized public void setterData(String name,String sex) {
        
        try {
            if (!isProduce) {
                this.wait();
            }

            this.name = name;
            Thread.sleep(10);
            this.sex = sex;
            
            isProduce = false;
            this.notifyAll();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    
    synchronized public void getterData() {

        try {
            if(isProduce) {
                this.wait();
            }
            System.out.println(this.name+"/"+this.sex);
            isProduce = true;
            this.notifyAll();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }
}

  • 生產者
package com.test.thread;

import java.lang.Runnable;

public class Producer implements Runnable{
    
    private ShareRegion share = null;
    
    public Producer(ShareRegion share){
        this.share = share;
    }
    
    @Override
    public void run() {
        
        for (int i = 0; i < 50; i++) {
            if (i%2 == 0) {
                share.setterData("春哥", "男");
            }else {
                share.setterData("鳳姐", "女");
            }
        }
        
    }

    

}

  • 消費者
package com.test.thread;

import java.lang.Runnable;

public class Consumer implements Runnable{
    
    private ShareRegion share = null;
    public Consumer(ShareRegion share){
        this.share = share;
    }
    
    @Override
    public void run() {
        // TODO Auto-generated method stub
        for (int i = 0; i < 50; i++) {
            share.getterData();
        }
    }

}

相關文章