Thread insecure threads can cause conflicts when accessing resources.
Examples such as the following
Package Com.test.thread;public class Testconfilict {/** * @param args */public static void main (string[] args) {Counter Co Unter=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;}}
This example is originally intended to increase from 0 to 10000, then if it is a single thread, the output is 100000. We do this in a multi-threaded way, with each thread responsible for an increase of 10 and a total of 10,000 threads.
We look at the results and we can find
We can see that the output is not the same, and, is not 100000, which indicates that the thread is unsafe, that is, the same resource to operate the time of the conflict, in particular, when the increase, because there is no resource protection, causing multiple threads to enter the added code at the same time.
Then, we can use the lock-up approach to solve the problem.
Package Com.test.thread;public class Testconfilict {/** * @param args */public static void main (string[] args) {Counter Co Unter=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;}}
As we can see, the output results
And each time is the same, indicating the use of lock-in way, so that the thread is safe.
Java thread is not secure