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();
            
        }
    
    }
  • 相关阅读:
    CSS实现文字上标、下标
    Inellij idea创建javaWeb以及Servlet简单实现
    利用Intellij+MAVEN搭建Spring+Mybatis+MySql+SpringMVC项目详解
    IntelliJ IDEA使用教程一 介绍&安装&配置
    JavaScript定时器实现的原理分析
    将 Django 应用程序部署到生产服务器
    html中的table导出Excel (亲测有用(●'◡'●))
    HTML用JS导出Excel的五种方法
    JS 导出网页中Table内容到excel
    Python数据库连接池实例——PooledDB
  • 原文地址:https://www.cnblogs.com/zk753159/p/5023832.html
Copyright © 2011-2022 走看看