线程不安全之线程在访问资源时候会导致冲突。
例如下列的例子
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;
}
}
我们看结果可以发现
我们可以看到,输出结果都不相同,而且,都不是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;
}
}
我们可以看到,输出结果
而且每次都是相同的,说明用加锁的方式,使得线程安全了。