• Java 线程不安全问题分析


    当多个线程并发访问同一个资源对象时,可能会出现线程不安全的问题

    public class Method implements Runnable {
    	private static int num=50;
    	 public void run() {
    		for(int i=0;i<50;i++){
    			eat();
    		}
    	}
    	 synchronized private void eat(){
    		if(num>0){
    			System.out.println(Thread.currentThread().getName()+"吃了编号为"+num+"的苹果!");
    			try {
    				Thread.sleep(10);
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    			num--;
    		}
    	}
    	public static void main(String[] args) {
    		Thread t=new Thread();
    		 Method a=new  Method();
    		new Thread(a,"小A").start();
    		new Thread(a,"小B").start();
    		new Thread(a,"小C").start();
    		
    	}
    }
    
    public class Method_1 implements Runnable {
    	private static int num = 50;
    
    	public void run() {
    		for (int i = 0; i < 50; i++) {
    			synchronized (this) {
    				if (num > 0) {
    					System.out.println(Thread.currentThread().getName() + "吃了编号为" + num + "的苹果!");
    					try {
    						Thread.sleep(10);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					num--;
    				}
    			}
    		}
    	}
    
    	public static void main(String[] args) {
    		Method_1 m = new Method_1();
    		new Thread(m, "小A").start();
    		;
    		new Thread(m, "小B").start();
    		;
    		new Thread(m, "小C").start();
    		;
    	}
    
    }
    

     

     

  • 相关阅读:
    ES6中的模板字符串使用方法
    windows下手动安装composer
    搬运 centos7.2 apache 绑定二级目录 访问依然是apache页面
    博客园样式修改
    Linux系统小知识
    Tcahce Stashing Unlink Attack
    vps+v_2_ray+proxychains
    环境问题记录
    web
    2020BJDCTF
  • 原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6665434.html
Copyright © 2020-2023  润新知