zoukankan      html  css  js  c++  java
  • 多线程生产消费的经典例子

    资源类

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

    要特别注意标记的操作。

    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();
            
        }
    
    }
  • 相关阅读:
    去除aspx生成的页面最开始的空行
    单个方框内图片垂直水平居中和等比例缩小(支持所有浏览器)
    .net里怎样在Main方法之前执行代码?
    WIN7系统盘空间不够用解决办法
    语音识别工具箱之HTK安装与使用
    一个VC中的DLL导出类的例子
    c++ 随机数 产生不重复的随机数
    android开发 NDK 编译和使用静态库、动态库
    c++指针 初识
    c++ UTF8和Unicode 互转
  • 原文地址:https://www.cnblogs.com/zk753159/p/5023832.html
Copyright © 2011-2022 走看看