zoukankan      html  css  js  c++  java
  • java中锁的应用(synchronized)

         在面试菜鸟的时候碰到的锁的编程问题,没答好,记录一下:

    package com.xielu.test;
    
    /**
     * Hello world!
     *
     */
    public class App 
    {
        private Object lock = new Object();
        private static int cnt = 1;
        private static final int MAX = 100;
        public static void main( String[] args )
        {
            Thread th1 = new Thread(){
                @Override
                public void run(){
                    synchronized(lock){
                        while(cnt <= MAX){
                            if(cnt%2 != 0){
                                System.out.println(cnt);
                                cnt++;
                                lock.notifyAll();
                            } else{
                                try{
                                    lock.wait();
                                }catch(Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            };
            Thread th2 = new Thread(){
                @Override
                public void run(){
                    synchronized(lock){
                        while(cnt <= MAX){
                            if(cnt%2 == 0){
                                System.out.println(cnt);
                                cnt++;
                                lock.notifyAll();
                            } else{
                                try{
                                    lock.wait();
                                }catch(Exception e){
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            };
    
            th1.start();
            th2.start();
        }
    }
    

      

  • 相关阅读:
    python主成分分析
    matplotlib绘图pie
    cpu监控:mpstat命令
    cpu监控:dstat
    MongoDB--安装部署
    Linux-网络管理
    Apache 虚拟主机配置
    Apache 访问控制
    Apache 域名跳转配置
    Apache 日志管理
  • 原文地址:https://www.cnblogs.com/spillage/p/15470879.html
Copyright © 2011-2022 走看看