zoukankan      html  css  js  c++  java
  • 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();
    		;
    	}
    
    }
    

     

     

  • 相关阅读:
    题解报告:hdu 2062 Subset sequence
    CSS3滑块菜单
    CSS3环形动画菜单
    可折叠显示的发光搜索表单
    Tab动画菜单
    侧边自定义滚动条
    css3条纹边框效果
    css3图片过滤效果
    CSS3图片悬停放大动画
    CSS3响应式侧边菜单
  • 原文地址:https://www.cnblogs.com/jiangxifanzhouyudu/p/6665434.html
Copyright © 2011-2022 走看看