码迷,mamicode.com
首页 > 编程语言 > 详细

java线程不安全

时间:2014-09-25 23:29:18      阅读:311      评论:0      收藏:0      [点我收藏+]

标签:blog   http   java   ar   for   2014   art   问题   on   

线程不安全之线程在访问资源时候会导致冲突。

例如下列的例子

package com.test.thread;

public class TestConfilict {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Counter counter=new Counter();
		
		for(int i=0;i<10000;i++)
		{
			(new TestThread(counter)).start();
			
		}
		
		

	}

}
class TestThread extends Thread
{
	private Counter counter;
	public TestThread(Counter counter)
	{
		this.counter=counter;
	}
	public void run()
	{
		
		counter.add(1);
		System.out.println(counter.get());
	}
}
class Counter
{
	protected int count=0;
	public void add(int value)
	{
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
	}
	public int get()
	{
		return count;
	}
}


这个例子原意就是从0增加到10000,那么如果是单线程的话,输出结果就是100000。我们采用多线程的方法来做,每个线程负责增加10,一共是10000个线程。

我们看结果可以发现

bubuko.com,布布扣


bubuko.com,布布扣


bubuko.com,布布扣


我们可以看到,输出结果都不相同,而且,都不是100000,这说明了线程不安全,也就是对同一个资源进行操作的时候,产生了冲突,具体来说,就是在增加的时候,因为没有资源保护,导致多个线程同时进入了增加的代码。

那么,我们可以采用加锁的方式来解决问题。

package com.test.thread;

public class TestConfilict {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		Counter counter=new Counter();
		
		for(int i=0;i<10000;i++)
		{
			(new TestThread(counter)).start();
			
		}
		
		

	}

}
class TestThread extends Thread
{
	private Counter counter;
	public TestThread(Counter counter)
	{
		this.counter=counter;
	}
	public void run()
	{
		
		counter.add(1);
		System.out.println(counter.get());
	}
}
class Counter
{
	protected int count=0;
	public synchronized void add(int value)
	{
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
		count=count+value;
	}
	public int get()
	{
		return count;
	}
}


我们可以看到,输出结果

bubuko.com,布布扣

而且每次都是相同的,说明用加锁的方式,使得线程安全了。

java线程不安全

标签:blog   http   java   ar   for   2014   art   问题   on   

原文地址:http://blog.csdn.net/itbuluoge/article/details/39558065

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!