首页 > 编程语言 > 详细

多线程采用不同的方法操作一个资源的例子

时间:2015-12-06 17:38:46      阅读:265      评论:0      收藏:0      [点我收藏+]

资源类

两个不同的方法,都是同步方法,当一个线程调用一个同步方法时,另外一个线程是不能调用另一个同步方法。

要特别注意标记的操作。

notify()执行后,如果这个线程后面还是程序未执行完,要先执行完,才会让出对象的锁。

public class ResDemo {
    private int num;
    private boolean flag;
    public ResDemo(int num, boolean flag) {
        super();
        this.num = num;
        this.flag = flag;
    }
    public synchronized void pro(){
        if(flag){
            System.out.println("仓库有货,不用生产");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.flag=true;
        this.num++;
        System.out.println(Thread.currentThread().getName()+"生产商品:::::"+num);
        notify();
    }
    public synchronized void sumer(){
        if(!flag){
            System.out.println("仓库里没有货,不能消费");
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.flag=false;
        this.num--;
        System.out.println(Thread.currentThread().getName()+"消费商品::::::"+num);
        notify();
        
    }

}

第一个线程

public class Thread_1 implements Runnable{
    private ResDemo resdemo;
    
    public Thread_1(ResDemo resdemo) {
        super();
        this.resdemo = resdemo;
    }

    @Override
    public void run() {
        for(int i=0;i<10;i++){
            this.resdemo.pro();
        }
        
        
        
    }

}

第二个线程

public class Thread_2 implements Runnable{
    private ResDemo resdemo;
    
    public Thread_2(ResDemo resdemo) {
        super();
        this.resdemo = resdemo;
    }

    @Override
    public void run() {
        for(int i=0;i<10;i++){
            this.resdemo.sumer();
        }
        
        
    }

}

测试类

public class Test {
    public static void main(String[] args){
        ResDemo resdemo=new ResDemo(0, false);
        Thread thread1=new Thread(new Thread_1(resdemo),"thread1");
        Thread thread2=new Thread(new Thread_2(resdemo),"thread2");
        thread2.start();
        thread1.start();
        
    }

}

 

多线程采用不同的方法操作一个资源的例子

原文:http://www.cnblogs.com/zk753159/p/5023832.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!