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();
		;
	}

}

 

 

 

posted @ 2017-04-04 16:57  *小嘻嘻*  阅读(445)  评论(0编辑  收藏  举报